[Tutor] A better way to estimate the value of Pi?

Steven D'Aprano steve at pearwood.info
Mon Oct 17 18:47:02 CEST 2011


bob gailer wrote:

> It is not crucial here - but you must recognize that your program uses floating 
> point numbers, which  almost always are an approximation to the
> "real" value.
> 
> For example (assuming decimal numbers):
> 
>  >>> 4/3.0
> 1.3333333333333333 (followed by an unending number of 0's).

Actually no, it is not followed by an unending number of zeroes. That 
would imply that floats had infinite precision, but 4/3.0 was merely 
calculated inaccurately. That's not the case: floats have a finite 
precision, but are (or at least, should be) accurate to within the 
limitations of that precision.

The exact value for 4.0/3 is actually:

1.3333333333333332593184650249895639717578887939453125

which is the closest possible binary fraction to 4/3.


> The "real" value of 4/3.0  is 1 followed by an unending number of 3's.
> 
> Each successive fraction's floating point value will be "off" by some relatively 
> small value. Those errors will probably add up.
> 
> Another limitation of floating point numbers is that there is a maximum and a 
> minimum exponent. Eventually the fractions will be too small to convert to 
> float, raising an overflow exception.

I don't think you need to worry about that. It takes a pretty big 
denominator before overflow will occur: a googol won't do it:

 >>> 4.0/10**100
4.0000000000000001e-100

Even though the series given is very slow to converge (3000000 terms is 
only accurate to 6 decimal places), I expect that it will converge 
before the terms overflow. It might take many hours or days of 
processing though.


> Allof this raises the question - what computer algorithms successively 
> approximate pi exactly?

Er, by definition you can't APPROXIMATE something EXACTLY. But see here 
for more approximations to π

http://en.wikipedia.org/wiki/Approximations_of_%CF%80



-- 
Steven


More information about the Tutor mailing list