Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Cosine Problem

Tags:

c++

math

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 of "result" I get: 0.95533648912560598

However, when I run cos(.3) on the computers calculator I get: .9999862922474

So clearly there is something that I am doing wrong.

Any thoughts on what might be causing the difference in results?

I am running Win XP on an Intel processor.

Thanks

like image 241
CodeLikeBeaker Avatar asked Mar 20 '26 03:03

CodeLikeBeaker


1 Answers

The difference in results is because:

Your computer's calculator is returning the cosine of an angle specified in degrees. The C++ cos() function is returning cosine of an angle specified in radians.

The .2999999999 is due to the way floating point numbers are handled in computers. .3 cannot be represented exactly in a double. For details, I recommend reading What Every Computer Scientist Should Know about Floating Point Arithmetic.

like image 76
Reed Copsey Avatar answered Mar 21 '26 18:03

Reed Copsey