Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increasing floating point precision in Python [duplicate]

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?

like image 538
hkk Avatar asked Jan 12 '14 19:01

hkk


People also ask

Are floats more precise than doubles?

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.

Is Python float double 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.

Is double precision same as float?

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.


2 Answers

Try using Decimal.

Read Arbitrary-precision elementary mathematical functions (Python)original for more information

like image 156
albusshin Avatar answered Sep 20 '22 14:09

albusshin


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

like image 33
Max Noel Avatar answered Sep 20 '22 14:09

Max Noel