Possible Duplicate:
getting value of sine 180 as 1.22465e-16
I am calculating a point on the circumference of the circle. I have the radius and the center point of the circle. Here you would say, big deal, there is a direct formula for the same. Yeah, angle is in rad
x = x + r*sin(angle)
y = y + r*cos(angle)
Okay, now the problem here is even though i am passing angle in radians. Yet I dont get correct answers for the below mentioned angle
for 90 degree (rads = 1.5708) i get y axis = -4.3774e-08
for 180 degree (rads = 3.14159) i get x axis = -8.74228e-08
for 270 degree (rads = 4.71239) i get y axis = 1.19249e-08
for 360 degree (rads = 6.28319) i get x asix = 1.74846e-07
I am converting Degree to Radians with
return degrees * M_PI / 180;
I am not sure as to why this is happening. There must be something seriously wrong.
Here is code used for conversion
float angle = DegreesToRadians(90);
float x = sin(angle);
float y = cos(angle);
Can anyone help me with this?
M_PI
is defined in "math.h" as
#define M_PI 3.14159265358979323846264338327950288
which is only approximately the (irrational) number Pi. Therefore
cos(M_PI/2), sin(M_PI), cos(3*M_PI/2), sin(2*M_PI)
are only approximately zero. Pi cannot be represented exactly as a float
or double
.
From your output I assume that you used float
.
Since the number of significant digits of a float
is about 7, and the slope (first derivative) of sin()
and cos()
at that points is +/- 1
, I would say that the results are as good as you can expect. Working with double
would give better results, but not exactly zero.
So there is nothing seriously wrong, you just can't expect the result of a floating point computation to be exact.
To add a comment to a duplicate question...
One alternative is to use grads or degrees instead of radians, so that the multiples of full circles, as well as multiples of each quadrant are integers and also the sines and cosines of those arguments can be represented exactly.
Also one has to marvel how well some implementations of math libraries handle multiples of pi: as the representation of pi in floats or doubles is off from the true value by some small amount delta, then it follows that N*(pi+-delta) is off from the true value by N*delta. Consequently in a well written library sin((pi/2)+(2*pi)*n) increases with n; with poorly written library, the argument is evaluated modulo approximation of 2*pi, giving exactly the same offset for every n.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With