Re: Calculating Pi [message #53252 is a reply to message #53250] |
Sun, 01 April 2007 10:18   |
lasse
Messages: 48 Registered: February 2007
|
Member |
|
|
On 1 Apr, 18:07, "Braedley" <mike.braed...@gmail.com> wrote:
> Does anyone have code that can calculate pi to an arbitrary
> precision? This is purely an academic endeavour.
>
> Actually that's a lie. This is just so that I can show others up.
Hi,
I remembered that there was a Monte Carlo mehtod to do this and the
following came up after a quick search. This is probably not very
efficient, but very instructive, since you can actually paint the
circle and the square on piece of paper and have your kids throw
stones at it... anyway, here we go:
If a circle of radius R is inscribed inside a square with side length
2R, then the area of the circle will be pi*R^2 and the area of the
square will be (2R)^2. So the ratio of the area of the circle to the
area of the square will be pi/4.
This means that, if you pick N points at random inside the square,
approximately N*pi/4 of those points should fall inside the circle.
This program picks points at random inside the square. It then checks
to see if the point is inside the circle (it knows it's inside the
circle if x^2 + y^2 < R^2, where x and y are the coordinates of the
point and R is the radius of the circle). The program keeps track of
how many points it's picked so far (N) and how many of those points
fell inside the circle (M).
Pi is then approximated as follows:
4*M
pi = ---
N
Although the Monte Carlo Method is often useful for solving problems
in physics and mathematics which cannot be solved by analytical means,
it is a rather slow method of calculating pi. To calculate each
significant digit there will have to be about 10 times as many trials
as to calculate the preceding significant digit.
cheers
lasse
|
|
|