Search code examples
objective-cciosmath.h

tan ( pi/2 ) in objective-c (math.h) not undefined


I wrote this test code:

NSLog(@"%g", tan(M_PI / 2.0));

and the output of the console is:

1.63312e+16

The issues is about approximation, right? Did I make some mistakes or the tan function of math.h really doesn't handle this case itself (returning me INFINITY) ? shall I handle theese input cases myself (example: when I get pi/2 input value I return an error message) or is there a better (more elegant) way to get the correct value ?

Thanks


Solution

  • Its because M_PI != real pi because it cannot be represented, so what you get from M_PI is approximation of pi, which its tangent is what you get.
    Edit: the following:

    printf("cos(M_PI / 2) = %.30f\nsin(M_PI / 2) = %.30f\n",
           cos(M_PI / 2), sin(M_PI / 2));
    

    will print

    cos(M_PI / 2) = 0.000000000000000061232339957368
    sin(M_PI / 2) = 1.000000000000000000000000000000
    

    Which shows cos(pi / 2) is non-zero.
    Doing the division will give

    1.63312393531953E16
    

    which is exactly what you get.