Reputation:
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?
Upvotes: 2
Views: 5381
Reputation: 94575
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: by the same reasoning as above, math.pi/2
(a float) is should be at worst at about 2e-16 from the exact value π/2. A Taylor expansion shows that math.sin(math.pi/2)
should be within 2e-32 from 1: the closest float (with their relative precision of about 1e-16) is therefore 1 (which is exactly represented by floats).
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).
Upvotes: 3