Calculate pi with python and recursion

Asked

Viewed 1,543 times

2

Calculate pi by formula pi=(s*32)**(1/3), being s=(1/1^3)-(1/3^3)+(1/5^3)... Amount of s determined by the user. It should be developed in with use of recursivity. I’m not getting the expected result, can help me find the error by doing the favor.

def test(n):
    if n <= 0:
        return False
    else:
        return True

def sum(n,a,p):
    if n == 0:
        return 0
    else:
        return (-1) ** a/ ((p + sum(n - 1, a + 1, p + 2) ** 3) * 32) ** (1 / 3)

n = int(input("Enter the number of the term you want to calculate: "))

if test(n):
    a = 2
    p = 1

    print("Total: ", sum(n, a, p))
else:
    print("Error")

1 answer

5


The main problem lies in its function sum, that is incorrectly calculating the sum value of the series.

One possible way to assemble this function is to analyze the individual series terms and get the generation rule for each element:

s=(1/1^3)-(1/3^3)+(1/5^3)....

The 2 important points here are:

first) The denominator of the fraction is formed by the cube of odd numbers

2nd) The sign of even terms is positive and odd is negative, or can also be analyzed as: the signal reverses each term (the first being positive)

The expression that generates a term, given its position (n) can be assembled as follows:

((-1)**(n+1)) + (1/(n*2-1)**3)

Being ((-1)**(n+1)) the part that reverses the signal:

n=1 => positivo
n=2 => negativo
n=3 => positivo
...

And (1/(n*2-1)**3) is the part that calculates the value of the term: 1 divided by an odd number cubed.

The recursive function serie can then be obtained thus:

def serie(n):
  if n == 0:
    return 0
  else:
    return serie(n-1) + ((-1)**(n+1)) * (1 / (n*2-1)**3)

OBS: sum is an internal Python function. Try to use different names of the internal functions for your functions

From the result of a series position, you can calculate the value of PI by the second formula.

Examples, varying the value of n:

(serie(1)*32)**(1/3)
3.1748021039363987

(serie(3)*32)**(1/3)
3.1437708364187786

(serie(10)*32)**(1/3)
3.1415260879295057

(serie(100)*32)**(1/3)
3.1415925860524654

(serie(1000)*32)**(1/3)
3.1415926535222463

(serie(2000)*32)**(1/3)
3.14159265358135
  • 2

    Thanks Gomiero for helping me solve this problem. Thanks also for the detailed explanation, it was very helpful your help.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.