13

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?

Hari Krishna Ganji
  • 1,647
  • 2
  • 20
  • 33

3 Answers3

46

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
K-ballo
  • 80,396
  • 20
  • 159
  • 169
  • Multiply the argument by `pi / 180` to convert from degrees to radians – Useless Jun 25 '12 at 18:26
  • 1
    Just so you know, `M_PI` isn't part of the standard: http://stackoverflow.com/questions/1727881/how-to-use-the-pi-constant-in-c – Electro Oct 04 '12 at 17:27
7

That's the tangent of your angle (30 radians.) if you are looking for the tangent of 30 degrees, you must convert your angle to radians first.

Jonathan Grynspan
  • 43,286
  • 8
  • 74
  • 104
1

I guess in C the tan Function requires you to Input Radians as an argument and not The actual degree value.

so for Tan 30 , you would have to convert your 30 degrees to radian. Keep in Mind that 360 degrees is 2*Pi radian so 30 degress would be (1\6 * Pi)th of a radian.

so tan(1\6 * Pi) would give you the correct answer. where Pi is 3.142

rav3451
  • 41
  • 6
  • @HighPerformanceMark .. Yup.. you are right, I seemed to have left out the 2 there.. I have corrected it now... thanks – rav3451 Jun 27 '12 at 13:26