C ++ cosine problem
I have the following code using C ++:
double value = .3;
double result = cos(value);
When I look at the values ββin the locals window for "value" it shows 0.2999999999
Then when I get the value "result" I get: 0.95533648912560598
However, when I run cos (.3) in the computers calculator I get: .9999862922474
It's so clear what I am doing wrong.
Any thoughts on what might be causing the difference in results?
I am running Win XP on an Intel processor.
thank
source to share
The difference in results is that:
Your computer calculator returns the cosine of an angle given in degrees. The C ++ cos () function returns the cosine of an angle given in radians.
.2999999999 is explained by the way floating point numbers are handled in computers..3 cannot be represented exactly in double. For more information, I recommend reading What Every Computer Scientist Should Know About Floating Point Arithmetic.
source to share
When I look at the values ββin the locals window for "value" it shows 0.2999999999
In short, your calculator uses decimal arithmetic, while your C ++ code uses binary arithmetic ( double
is a binary floating point number). A decimal number 0.3
cannot be represented exactly as a binary floating point number. Read What Every Computer Scientist Should Know About Floating Point Arithmetic , which explains the implications in more detail.
source to share
C ++ does not accurately represent floating point numbers due to the insane amount of storage it would take to get the infinite precision needed. To demonstrate this, try the following:
double ninth = 1.0/9.0;
double result = 9.0 * ninth;
This should give a value in the result .99999999999
So essentially, you need to compare floating point values ββwithin a small epsilon (I tend to use 1e-7). You can do a bitwise string comparison, but that consists of converting the floating point memory to a sizeof (float) character array and then character comparison.
Another thing to check is if you are using degrees. The computer calculator uses degrees to calculate the cosine (note how the calculator's result is 0.99999 ... which is very close to 1. The cosine of zero is exactly 1), whereas the cosine function provided in <math> is in radians. Try multiplying your value by PI / 180.0 and see if the result is more stringent with your expectations.
source to share