Calculate pi with python and use of recursion

1

Calculate pi by the formula pi=(s*32)**(1/3) , being s=(1/1^3)-(1/3^3)+(1/5^3) ... Quantity of s determined by the user. Must be developed in using recursion. I can not get the expected result, they can help me find the error, please.

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")
    
asked by anonymous 01.09.2018 / 16:51

1 answer

4

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

A possible way to assemble this function is to analyze the individual terms of the series and obtain the generation rule for each element:

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

The 2 important points here are:

1st The denominator of the fraction is formed by the cube of odd numbers

2º) The sign of the even-numbered terms is positive and the odd-numbered is negative, or it can also be analyzed as:

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

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

Being ((-1)**(n+1)) the part that inverts 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 raised to the cube.

The recursive function serie can then be obtained as follows:

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 built-in 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
    
01.09.2018 / 21:10