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