Tim Peters added the comment:
Python's floats are emphatically not doing symbolic arithmetic - they use the
platform's binary floating point facilities, which can only represent a subset
of rationals exactly. All other values are approximated.
In particular, this shows the exact value of the approximation used for pi:
>>> import math
>>> from decimal import Decimal
>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')
That isn't the mathematical pi, but is the closest approximation representable
as a platform Python binary float (same as type "double" in the platform C).
Here's the difference between math.pi and a better decimal approximation to pi:
>>> Decimal(math.pi) - Decimal("3.141592653589793238462643383279502884")
Decimal('-1.224646799147353177224094238E-16')
So math.pi is a little bit smaller than the mathematical pi.
Mathematically, using the subtraction formula for sine:
sin(pi - e) = sin(pi)*cos(e) - sin(e)*cos(pi) =
0*cos(e) - sin(e)*-1 =
0 + sin(e) =
sin(e)
So mathematically sin(pi - e) = sin(e), and if |e| is close to 0 then sin(e) ~=
e.
For that reason, it's not a coincidence that the result you got for
math.sin(math.pi) = 1.22464...e-16 is approximately equal to the difference
(shown above) between the mathematical pi and math.pi. It's not due to gross
inaccuracy in sine, it's due to that pi isn't exactly representable as a Python
float.
Note that this has nothing to do with Python specifically. You'll see the same
kind of behaviors in any language exposing the platform floating point
facilities.
If you need to do symbolic computations, then you need much fancier facilities.
----------
nosy: +tim.peters
resolution: -> not a bug
status: open -> closed
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue27440>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com