Search code examples
objective-cddmathparser

sin(pi()) does not return 0 in DDMathParser


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.


Solution

  • 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