Why is math.pi slightly wrong?

Mark Dickinson dickinsm at gmail.com
Thu May 22 13:32:17 EDT 2008


On May 22, 12:32 pm, "Dutton, Sam" <Sam.Dut... at itn.co.uk> wrote:
> I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.)
>

There are two effects here:

(1) pi isn't exactly representable as a floating-point number,
so math.pi is merely an approximation to it, and

(2) the value 3.1415926535897931 that you see when you print
pi is itself an approximation to the actual value of math.pi.
math.pi is exactly equal to 884279719003555/281474976710656,
which is the closest C double to the actual value of pi.

The problem in (2) occurs because floating-point numbers
are stored in binary, but printed in decimal.

Mark



More information about the Python-list mailing list