-2

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)

1 Answers1

3

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.

zvone
  • 18,045
  • 3
  • 49
  • 77
  • 1
    a little over `6` isn't really approximately equal to zero? – adeneo Dec 13 '15 at 17:05
  • 2
    @adeneo, `a little over 6 `? `6.123233995736766e-17` is so very much far away from 6. That's `6 * 10 ^ -17`. – Darin Dimitrov Dec 13 '15 at 17:05
  • @DarinDimitrov - there could at least be a little explanation on scientific notation ? – adeneo Dec 13 '15 at 17:06
  • Well, I obviously wouldn't mind a value very close to 0 instead of actual 0, but could you please explain whether `6.123233995736766e-17` is closer to 0 or 6? – Shahar Nacht Dec 13 '15 at 17:06
  • 1
    @adeneo, this is standard scientific notation. There's no need of further explanation. – Darin Dimitrov Dec 13 '15 at 17:07
  • 3
    @adeneo 6.123233995736766e-17 is 0.00000000000000006123233995736766 – zvone Dec 13 '15 at 17:08
  • @DarinDimitrov - I know that, but I'm guessing not everyone does, nor do they know why javascript, and other languages, don't calculate correctly. – adeneo Dec 13 '15 at 17:08
  • Just saying it's "approximate" doesn't seem like a very good answer to me, but it seems I'm wrong. – adeneo Dec 13 '15 at 17:09
  • 1
    @adeneo, that's why in my comment I have linked to an article about `What Every Computer Scientist Should Know About Floating-Point Arithmetic` : https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html So that they don't be confused. – Darin Dimitrov Dec 13 '15 at 17:09
  • @DarinDimitrov - and that's why I in my comment have linked to a question that actually answers this question. And yes, I've read the article you've linked to a long time ago – adeneo Dec 13 '15 at 17:11