Increasing floating point precision in Python

本秂侑毒 提交于 2019-12-22 04:57:09

问题


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?


回答1:


Try using Decimal.

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




回答2:


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




回答3:


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?




回答4:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!