1
let e = Math.sin(Math.PI);
document.write(e)

The expression result is 1.2246467991473532e-16 but I want to get 0 but if I use

e = Math.sin(Math.PI+epsilon)

epsilon is a very small number like 1e-10 then do not round the expression to 0.

If i use Math.cos(Math.PI/2) it give me 6.123233995736766e-17 but I want to get 0

So I want to make sure that it will give me the accurate answer every time.

  • Math.sin(Math.PI); does not return 0 because Math.PI is not π. its irrational https://0.30000000000000004.com/ – john Smith Jan 16 '21 at 19:11
  • But if i use Math.cos(Math.PI) it give me the right answer -1 –  Jan 16 '21 at 19:17
  • Does this answer your question? [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Peter O. Jan 16 '21 at 22:48

1 Answers1

3

What you are seeing is (IEEE 754 64-bit double-precision) floating-point round-off error, and it is working as intended. The result "1.2246467991473532e-16" is in scientific notation, representing an extremely small value of about 1.22×10⁻¹⁶.

Like John said, the cause of this error is that π is not exactly represented as a floating point value, introducing (an extremely small) round-off error. The 64-bit float value closest to π is about

Math.PI = 3.141592653589793116...

vs. the exact value being closer to

π = 3.141592653589793238...

for an error of about 1.22×10⁻¹⁶. The sine function satisfies the "reduction formula"

sin(π − x) = sin(x).

Using that, we get

sin(Math.PI) ≈ sin(π - 1.22×10⁻¹⁶)
             = sin(1.22×10⁻¹⁶)
             ≈ 1.22×10⁻¹⁶,

where the last step uses that sin(x) ≈ x for x near 0 (first-order Taylor approximation, aka small angle approximation). This explains the result "1.2246467991473532e-16" that you saw for sin(Math.PI).

If you don't want to see this small round-off error, you can round the result with something like result.toFixed(9) (see Number.toFixed()).

For a gentle intro to the quirks of floating point, see "What Every Programmer Should Know About Floating-Point Arithmetic" or "Why don’t my numbers add up?".

Pascal Getreuer
  • 2,906
  • 1
  • 5
  • 14