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
Thanks Gomiero for helping me solve this problem. Thanks also for the detailed explanation, it was very helpful your help.
– Henrique Carneiro