0

I am encountering a floating point precision issue, does anybody know why this happens? Why is it that the cosine function is affected, but not he sine function.

Math.sin(90 * Math.PI / 180);
// returned: 1, expected: 1

1 - Math.sin(90 * Math.PI / 180);
// returned: 0, expected: 0


Math.cos(90 * Math.PI / 180);
// returned: 6.123233995736766e-17, expected: 0

1 - Math.cos(90 * Math.PI / 180);
// returned: 0.9999999999999999, expected: 1
thephpdev
  • 1,097
  • 10
  • 25
  • This is just a common issue with all languages, but mainly because using floating point math leads to rounding errors. Your best best is just rounding it unfortunately... – Adam William Larson Dec 15 '15 at 21:14
  • But why is it just cosine that's affected, and not the sine function? (updated my question to reflect this comment). – thephpdev Dec 15 '15 at 21:16
  • @RobertoAureli, could you please elaborate? I'm not quite sure what you mean there. Thanks in advance. – thephpdev Dec 15 '15 at 21:43
  • https://en.m.wikipedia.org/wiki/0.999 – Roberto Aureli Dec 15 '15 at 21:44
  • Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/q/588004/1529630) – Oriol Dec 15 '15 at 22:39
  • @Oriol, no it's not. My question is it, with the equation demonstrated in my example, that only the cosine function returned an incorrect value? Sine returned exactly 1 or 0, whereas cosine did not. – thephpdev Dec 15 '15 at 22:41
  • Just like `0.1+0.1 == 0.2` but `0.2+0.1 != 0.3` – Oriol Dec 15 '15 at 22:44

1 Answers1

1

The canonical answer to this one is What Every Computer Scientist Should Know About Floating-Point Arithmetic

With a little more trying you will find examples for "unexpected" results with the sine function.

E.g. Math.sin(180 * Math.PI / 180);

Ludwig Schulze
  • 2,155
  • 1
  • 17
  • 36
  • I know why floating point accuracy errors occur, my question is, why is it just the cosine that returns an incorrect value for the equation demonstrated? – thephpdev Dec 15 '15 at 22:39