简体   繁体   中英

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
        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 (eg more digits) of the calculation? Does Python support more precise floating points, or will I have to use some external library?

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.

See Python floating point arbitrary precision available?

Try using Decimal .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM