0

I'm making a calculator app using DDMathParser. The problem I'm facing is sin(pi()) doesn't return 0 but a trivial number like 1.2246...e-16. I'm just wondering is there any way to convert it to 0? Thank you.

user
  • 85
  • 3
  • 13

1 Answers1

1

The -description method on NSNumber does not accurately represent the underlying number:

NSLog(@"%f", sin(M_PI));    // logs 0.000000
NSLog(@"%@", @(sin(M_PI))); // logs 1.224646799147353e-16

To work around this, you can pull out the -doubleValue of the NSNumber, and that should give you 0:

NSLog(@"%f", @(sin(M_PI)).doubleValue); // logs 0.000000
Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
  • You are cheating here: `M_PI` is not exactly π, and therefore `sin(M_PI)` is not exactly zero. `NSLog(@"%f", sin(M_PI))` logs 0.000000 because it rounds to a precision of 6 decimal digits, not because it is "more accurate" than the description method of NSNumber. – Martin R Jul 16 '16 at 21:13