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?
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
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.
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.
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.
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