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

+2


source to share


6 answers


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.

+20


source


cos (.3 radians) = 0.95533 ...



cos (.3 degrees) = 0.99998 ...

+10


source


cos (0.3) = 0.99998629224742679269138848004408 using powers

cos (0.3) = 0.95533648912560601964231022756805 using radians

+4


source


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.

+3


source


Your calculator uses degrees. For example:

>>> import math
>>> math.cos (.3)
0.95533648912560598
>>> math.cos (.3 * math.pi / 180)  # convert to degrees
0.99998629224742674

      

+2


source


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.

+2


source







All Articles