tags:

views:

195

answers:

3

I have a strange problem with the standard cos function of cmath/math.h. Apparently under some circumstances it returns a wrong or simply undefined value.

#include <cmath>
#include <iostream>

int main()
{
 double foo = 8.0 * 0.19634955; // 1.5707964
 double bla = std::cos(foo);    // should be 0.9996242168245
 std::cout << bla << std::endl; // cos returns -7.32051e-008

 return 0;
}

If the input value for cos is 1.5707964 for example, cos returns -7.32051e-008 (when using doubles, with floats it's -4.XYZe-009).

Am I missing something really basic and simple here...?

+15  A: 

cos expects radians, you are giving it degrees. Multiply your input value by 3.14159/180, and you will get the right answer.

Ned Batchelder
+1. But answering faster than me should be banned
Yacoby
Woops, yeah, it was something simple after all, thx ;)
Spooky
Spooky: glad it worked. Standard stackoverflow etiquette is to accept the answer if it is correct.
Ned Batchelder
+1  A: 

I don't know if you're passing radian or degrees... But your value of foo is near PI/2. So you get cos(foo) = 0 and sin(foo) = 1 (what you expected?)

Julio
A: 

cos(PI/2) = 0, not 1.

Alexandre C.