I came across some weird behavior by math.cos()
(Python 3.11.0):
>>> import math
>>> math.cos(math.pi) # expected to get -1
-1.0
>>> math.cos(math.pi/2) # expected to get 0
6.123233995736766e-17
I suspect that floating point math might play a role in this, but I'm not sure how. And if it did, I'd assume Python just checks if the parameter equaled math.pi/2
to begin with.
I found this answer by Jon Skeet, who said:
Basically, you shouldn't expect binary floating point operations to be exactly right when your inputs can't be expressed as exact binary values - which pi/2 can't, given that it's irrational.
But if this is true, then math.cos(math.pi)
shouldn't work either, because it also uses the math.pi
approximation. My question is: why does this issue only show up when math.pi/2
is used?
The result for math.cos(math.pi)
will have a similar degree of inaccuracy, however -1.0 + 6e-17
cannot be represented in floating point precision, so you just get -1.0
. This can be demonstrated so:
>>> -1.0000_0000_0000_001
# -1.000000000000001
>>> -1.0000_0000_0000_0001
# -1.0