How can I write a function which will return pi (π) to a given number of decimal places?
Speed is not a concern. I've been looking at http://bellard.org/pi/, but I still don't understand how to get the nth digit of pi.
How can I write a function which will return pi (π) to a given number of decimal places?
Speed is not a concern. I've been looking at http://bellard.org/pi/, but I still don't understand how to get the nth digit of pi.
My two cents... This might not be the fastest, but I think it's quite easy to understand. I came up with it myself during a math lecture, and I haven't really seen it anywhere else in literature. Either I'm a genius, really stupid, or don't really pay attention to reading books about math, or all of the above... :)
Anyway... Start with the unit circle. We know that x^2+y^2=1, so y=sqrt(1-x^2). We also know that the area of the unit circle is PI. If we now take the integral of the function sqrt(1-x^2) in the range 0 to 1, we will get a quarter of PI. So multiply it by 4 to get PI:
If we would try to solve this analytically, I'm sure we would just get PI back. But it's quite easy to write a program to solve it numerically. The following one is in C:
Running it with the above setting for
interval
, we get:So 10,000,000 iterations give 6 correct decimals. Not the most efficient, but it's my baby... :)
I believe the algorithm you're looking for is what's known as a "Spigot Algorithm." One particular kind is the BBP (Bailey-Borwein-Plouffe) formula.
I believe that's what you're looking for.
"π IN THE MANDELBROT SET" explores the curious relationship between a sequence of points on the complex plane and how computing their "Mandelbrot number" (for lack a better term ... the number of iterations required to determine that the points in the sequence are not members of the Mandelbrot set) relates to PI.
Practical? Probably not.
Unexpected and interesting? I think so.
I'd start with the formula
Google will easily find a proof for this formula that normal human beings can understand, and a formula to calculate the arc tangent function. This will allow you to calculate a few thousand decimal digits of pi quite easily and quickly.
As an alternative to JeffH's method of storing every variation, you can just store the maximum number of digits and cut off what you don't need:
http://codepad.org/6mqDa1zj