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?
double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.
Python float values are represented as 64-bit double-precision values. The maximum value any floating-point number can be is approx 1.8 x 10308.
Double-precision floating-point format (sometimes called FP64 or float64) is a computer number format, usually occupying 64 bits in computer memory; it represents a wide dynamic range of numeric values by using a floating radix point.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With