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
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).