I noticed a glitch while using math.sin(math.pi). The answer should have been 0 but instead it is 1.2246467991473532e-16. If the statement is math.sin(math.pi/2) the answer is 1.0 which is correct. why this error?
-
2Well it's pretty damn close, isn't it? – Chris Martin Sep 02 '14 at 04:13
-
Limited-precision floating-point numbers have limited precision and 0.0000000000000001 is very close to 0. – Ry- Sep 02 '14 at 04:14
-
math.sin(math.pi)=1.22e-16 but still math.sin(math.pi/2)=1.0 why? – Sep 02 '14 at 04:22
1 Answers
The result is normal: numbers in computers are usually represented with floats, which have a finite precision (they are stored in only a few bytes). This means that only a finite number of real numbers can be represented by floats. In particular, π cannot be represented exactly, so math.pi
is not π but a very good approximation of it. This is why math.sin(math.pi)
does not have to be sin(π) but only something very close to it.
The precise value that you observe for math.sin(math.pi)
is understandable: the relative precision of (double precision) floats is about 1e-16. This means that math.pi
can be wrong by about π*1e-16 ~ 3e-16. Since sin(π-ε) ~ ε, the value that you obtain with math.sin(math.pi)
can be in the worst case ~3e-16 (in absolute value), which is the case (this calculation is not supposed to give the exact value but just the correct order of magnitude, and it does).
Now, the fact that math.sin(math.pi/2) == 1
is not shocking: it may be (I haven't checked) that math.pi/2
(a float) is so close to the exact value π/2 that the float which is the closest to sin(math.pi/2
) is exactly 1. In general, you can expect the result of a function applied to a floating point number to be off by about 1e-16 relative (or be about 1e-16 instead of 0).

- 91,433
- 48
- 218
- 260
-
Different implementations of sine in computers can produce different results (http://en.wikipedia.org/wiki/Sine#Software_implementations). It may be, though, that it is desirable to have an implementation of sine return 1 for sin(π/2): maybe `math.pi/2` is so close to π/2 that `math.sin(math.pi/2)` should ideally be closer to 1 than to any other float. I reworded the last paragraph so as to make the discussion about sin(π/2) clearer. – Eric O. Lebigot Sep 03 '14 at 12:27