I have been trying to make a function that calculates pi to n digits using the Leibniz' formula. I am using the decimal module to be able to set how many decimal points I wish to output, but for some reason I always get the same number of points.
def my_leibniz(k,n):
pi_over_four = 0
getcontext().prec = n
for num in range(k):
pi_over_four += (-1.0)**num/(2.0*num + 1.0)
pie = 4*pi_over_four
return f'Your value of pi to {n} decimal spaces is ' + str(Decimal(pie))
The output is always in the form: 'Your value of pi to 3 decimal spaces is 3.140592653839794134995599961257539689540863037109375'
The value of Pi does change as I change k, but the number of decimal points is the same for whatever integer greater than 0 I put in for n.
I have looked through other code that uses the Decimal class to create this program using a difference method to calculate Pi, and can't see why my one is not working as expected.
The problem is that you're doing all of your math in float
s, and only converting to Decimal
at the very end.
Replace the line:
pi_over_four += (-1.0)**num/(2.0*num + 1.0)
with
pi_over_four += Decimal(-1)**num / (Decimal(2)*num + Decimal(1))
Which is the most direct equivalent, replacing each float
literal with a Decimal
constructor call.
(Technically, you only need one of the Decimal
constructor calls, and then the int
s will automatically be promoted to Decimal
during mixed arithmetic.)