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