# Continued fraction for pi

1. Jan 22, 2008

### mayeeta

1. The problem statement, all variables and given/known data

Via iteration. A continued fraction for pi is:

Write an algorithm to compute this to n terms using Matlab.

1st term would be 3+1/9

3. The attempt at a solution

p = '1';
for k = 1:n
p=3+(-1+2^n)/(3+p);
end
p

I'm very new to programming, and I can only think of this.

2. Jan 22, 2008

### HallsofIvy

Staff Emeritus
Have you checked it at all?

For the very first term, when n= 1, this is 3+ (-1+2)/(3+ 1)= 3+ 1/4, not 3+ 1/9.

If it were me, I think I would run the loop backwards, starting from n and going down to 1 because each fraction is used in the previous one.

Also you might want to check exactly what the "nth term" is. Do you just ignore the "new fraction" and just use denominator "6" for the last term?

Last edited: Jan 22, 2008
3. Jan 22, 2008

### mayeeta

I tried to do it backward, and I got this

p = ((2*n+1)^2)/6;
for k = n:-1:1
p = 6+(2*n-1)^2/p;
end
f=p+3

How to fix it? I think it's closer to the right answer.

4. Jan 25, 2008

### Gib Z

This all just may be very coincidental, but from this continued fraction is it possible to show $$\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}$$ from this? It just seems that it should have a nice connection, with the squares and the 6's in there and all.

5. Jan 26, 2008

### coomast

The limits seem a bit awkward. Mmmm, let's call the terms 1 2 3 4 5 6 which involve the squares of 1 3 5 7 9 11 respectively. This means that you can generalize it as n and 2n-1 to make things a bit more clear.

Now the last term is:

$$A=\frac{(2n-1)^2}{6}$$

Then the runner i goes from n-1 to 1 and determines the general intermediate result:

$$B=\frac{(2i-1)^2}{6+A}$$

Off course you need to set this value back to A for the next i-loop. You get finally in pseudo-code:

integer n,i
real A,B
input n
set A=(2n-1)^2/6
for i=n-1 downto 1 do
begin loop
calc B=(2i-1)^2/(6+A)
set A=B
end loop
output 3+A

Hope this makes it a little bit more clear.