I have arrived at a solution to the exercise 8.3 of "The Coder's Apprentice Learning Programming with Python 3" that is slightly differente form the author's solution. I wanted to ask here if it could be right.
The exercise's text is the follwing: The Grerory-Leibnitz series approximates pi as 4 ∗ ( 1/1 − 1/3 + 1/5 −1/7 + 1/9... ) . Write a function that returns the approximation of pi according to this series. The function gets one parameter, namely an integer that indicates how many of the terms between the parentheses must be calculated.
def leibnitz(n):
tot = 0
i=1
c=1
for x in range(0,n):
if c % 2 != 0:
tot = tot + (+1.0/i)
i=i+2
c=c+1
elif c % 2 == 0:
tot = tot + (-1.0/i)
i=i+2
c=c+1
return tot*4
print(leibnitz(98))
#by fixing a counter "c", we can manage to establish if the next fraction of the series will be a positive or a negative fraction. the first fraction in the series (1/1) is positive, so we start with a counter of "c" = 1 that is odd. then whenever a counter will be even, we consider a negative fraction and so on.
Is this solution right?
I had made an error with in the last version and updated it now.