问题
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...?
回答1:
cos expects radians, you are giving it degrees. Multiply your input value by 3.14159/180, and you will get the right answer.
回答2:
cos(PI/2) = 0, not 1.
回答3:
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?)
来源:https://stackoverflow.com/questions/1855441/cos-returns-wrong-values