troglodite troglodite - 1 year ago 129
Python Question

Increasing floating point precision in Python

I was working on a project to compute the Leibniz approximation for pi with the below code:

def pi(precision):
sign = True
ret = 0
for i in range(1,precision+1):
odd = 2 * i - 1
if sign:
ret += 1.0 / odd
ret -= 1.0 / odd
sign = not sign
return ret

However, the output value was always was 12 digits long. How can I increase the precision (e.g. more digits) of the calculation? Does Python support more precise floating points, or will I have to use some external library?

Answer Source