0

I just started learning Python and I am having a problem writing the function.

The following is an infinite series that calculates an approximation of π : π = 4/1 − 4/3 + 4/5 - 4/7 + 4/9 - 4/11 ...

I am trying to write a function that takes as a parameter a floating point value error and approximates the constant π within error by computing the above sum, term by term, until the absolute value of the difference between the current sum and the previous sum (with one fewer terms) is no greater than error. Once the function finds that the difference is less than error, it should return the new sum.

The following shows the execution of this function on some examples:

>>> aprPi(0.01)
3.1465677471829556
>>> aprPi(0.0000001)
3.1415927035898146

I still don't know how to compute it. Can someone help me?

This is what I have so far:

def aprPi(err):
    first  = 4/test(0) - 4/test(1)
    second = first + 4/test(2) - 4/test(3)
    n=4
    while abs(first - second) > err:
        first = second
        second = second + test(n)
        n +=1
    return second


def test(n):
    sum = 1
    for i in range(n):
        sum += 2

    return sum

Thank you

  • 2
    Can you please fix your indentation? – yasar Nov 04 '11 at 20:52
  • this also doesn't really sound like a python question, more like general programming. – samb8s Nov 04 '11 at 20:55
  • 4
    A Calculus note: That serie for PI is a veeery slowly converging one. – Avaris Nov 04 '11 at 20:59
  • By the way, you can sum up all you do into a `first= 0` and `second = 0` until the loop part, and you won't ever enter the loop, unless err is negative. And when you enter the loop, you won't ever get out of that loop, as first and second is always 0. – yasar Nov 04 '11 at 21:11
  • see http://stackoverflow.com/questions/347734/gauss-legendre-algorithm-in-python/347749#347749 – jfs Nov 04 '11 at 21:22

1 Answers1

1

You can do something like this:

mypie = 0
denominator = 1
sign = 1

while denominator < 100:
    mypie = mypie + (4.0 / denominator) * sign
    sign = -sign
    denominator = denominator + 2
yasar
  • 13,158
  • 28
  • 95
  • 160
  • I guess it depends on the version of python, but you might need to make it a float division, e.g. 4.0 – samb8s Nov 04 '11 at 20:58
  • You are right, I edited my post. I also should't have used sum as variable name as it is a built-in function name. – yasar Nov 04 '11 at 21:03