Monday 22 January 2018

javascript - Math.cos() gives wrong results





According to my understanding, and my calculator, cos(90
degrees)
equals 0.
In my code, I have a
function that allows me to type in degrees whenever I need
to:




function
deg(i)
{
return
i*Math.PI/180;
}


Although,
when calling Math.cos(deg(90)); the output I receive is
6.123233995736766e-17.



Why
could such a thing possibly
happen?




(Please excuse me for my bad
English)



Answer




deg(90) is
approximately equal to 90*Math.PI/180 and
your result is aproximately equal to
0.



So, everything is
fine ;)



Note that it has to be
approximate, because there is no way to represent π
precisely.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...