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.
Asked
Active
Viewed 143 times
0

user
- 85
- 3
- 13
-
No need for DDMathParser for that. Just use `sin(M_PI);`. – rmaddy Jan 30 '15 at 04:52
-
I'd like to convert any input expressions into a double value, so it's by far easier to write if I use a math parser. – user Jan 30 '15 at 06:00
1 Answers
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