Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Cos & Math.Sin in C#

I'm trying something that I thought should be reasonably simple. I have an angle, a position and a distance and I want to find the X,Y co-ordinates from this information.

With an example input of 90 degrees I convert the value to radians with the following code:

public double DegreeToRadian(float angle)
{
  return Math.PI * angle / 180.0;
}

This gives me 1.5707963267949 radians Then when I use

Math.Cos(radians)

I end up with an an answer of: 6.12303176911189E-17

What the heck is going on? The cosine of 90 degrees should be 0, so why am I getting such a deviance... and more importantly how can I stop it?

like image 574
elaverick Avatar asked May 21 '11 15:05

elaverick


4 Answers

you should use rounding

var radians = Math.PI * degres / 180.0;
var cos = Math.Round(Math.Cos(radians), 2);
var sin = Math.Round(Math.Sin(radians), 2);

the result would be: sin: 1 cos: 0

like image 81
Xhevo Avatar answered Sep 18 '22 02:09

Xhevo


See answers above. Remember that 6.12303176911189E-17 is 0.00000000000000006 (I may have even missed a zero there!) so it is a very, very small deviation.

like image 33
Edwin Groenendaal Avatar answered Sep 21 '22 02:09

Edwin Groenendaal


Let me answer your question with another one: How far do you think 6.12303176911189E-17 is from 0? What you call deviance is actually due to the way floating point numbers are internally stored. I would recommend you reading the following article. In .NET they are stored using the IEEE 754 standard.

like image 22
Darin Dimitrov Avatar answered Sep 19 '22 02:09

Darin Dimitrov


Read up on floating point arithmetic. It is never and can never be exact. Never compare exactly to anything, but check whether the numbers differ by a (small) epsilon.

like image 36
Pontus Gagge Avatar answered Sep 21 '22 02:09

Pontus Gagge