def calculateFraction(num):
if (num > 0):
return (-1)**(num) * 1/(num*2+1) + calculateFraction(num-1)
else:
return 1
print(4 * calculateFraction(10))
EDIT
Olivier's answer is extremely good, I wish I could upvote it several times.
In light of that I thought the OP may benefit from seeing a binary implementation of the above approach. That is to say, whenever recursing, send half the problem to one branch and the other half to another branch. (This means that, for example, asking for num=15 will result in a depth of 4 rather than a depth of 16.)
import inspect
def calculateFraction(num, end=0):
result = 0
depth = 'Depth({:d}){:s}>'.format(len(inspect.stack())-1, '='*(len(inspect.stack())-1)*2)
# If there are an odd number of parts to calculate, do the highest one now
if (((num-end+1)&1) == 1):
result += ((-1)**(num)) / (num*2+1)
print('{:s} Fraction part {:d} = {:f}'.format(depth, num, result))
num-=1
# If there are still any parts to calculate, do them recursively
# (There must be an even number, as we did the odd one previously)
# (That may leave 0 still to do, in which case the recursion is skipped)
if (num > end):
mid = ((num-end)>>1) + end
# Do the upper half of the remaining parts
print('{:s} Recursing to {:d},{:d}'.format(depth, num, mid+1))
result += calculateFraction(num, mid+1)
# Do the lower half of the remaining parts
print('{:s} Recursing to {:d},{:d}'.format(depth, mid, end))
result += calculateFraction(mid, end)
return result
print('Result: {:f}'.format(4*calculateFraction(10)))