Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Continued fraction for pi

  1. Jan 22, 2008 #1
    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

    I'm very new to programming, and I can only think of this.
  2. jcsd
  3. Jan 22, 2008 #2


    User Avatar
    Science Advisor

    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 by a moderator: Jan 22, 2008
  4. Jan 22, 2008 #3
    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;

    How to fix it? I think it's closer to the right answer.
  5. Jan 25, 2008 #4

    Gib Z

    User Avatar
    Homework Helper

    This all just may be very coincidental, but from this continued fraction is it possible to show [tex]\sum_{n=1}^{\infty} \frac{1}{n^2} = \frac{\pi^2}{6}[/tex] from this? It just seems that it should have a nice connection, with the squares and the 6's in there and all.
  6. Jan 26, 2008 #5
    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:


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


    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.
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook