In C, tan(30) gives me a negative value! Why?

Hari Krishna Ganji picture Hari Krishna Ganji · Jun 25, 2012 · Viewed 7.5k times · Source

I observe that my tan(float) function from the cmath library is returning a negative value.

The following piece of code, when run :

    #include <cmath>
    ....

    // some calculation here gives me a value between 0.0 to 1.0.
    float tempSpeed = 0.5; 

    float tanValue = tan(tempSpeed * 60);

    __android_log_print(ANDROID_LOG_INFO, "Log Me", "speed: %f", tanValue);

Gives me this result in my Log file:

    Log Me: speed `-6.4053311966`

As far as I remember

    tan(0.5*60) = tan(30) = 1/squareroot(3);

Can someone help me here as in why I am seeing a negative value? Is it related to some floating point size error? Or am I doing something really dumb?

Answer

K-ballo picture K-ballo · Jun 25, 2012

In C, tan and other trigonometric functions expect radians as their arguments, not degrees. You can convert degrees to radians:

tan( 30. * M_PI / 180. ) == 0.57735026918962576450914878050196