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
else:
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?
Try using Decimal
.
Read Arbitrary-precision elementary mathematical functions (Python)original for more information
Python's float
type maps to whatever your platform's C compiler calls a double
(see http://en.wikipedia.org/wiki/IEEE_floating_point_number).
The Python standard library also comes with an arbitrary-precision decimal module, called decimal
: http://docs.python.org/2/library/decimal.html
With Python's float, you get 15–17 digits of precision (if you are seeing fewer, you may need to use a different format specifier when printing).
If you need more, you'll need to use a different method (one that only uses integer arithmetic), or a different way to represent floating-point numbers.
The Leibniz formula converges extremely slowly - honestly, you won't live long enough for it get 12 digits of accuracy. Click here for one way to accelerate it enormously.
来源:https://stackoverflow.com/questions/21079282/increasing-floating-point-precision-in-python