简体   繁体   English

提高Python中的浮点精度

[英]Increasing floating point precision in Python

I was working on a project to compute the Leibniz approximation for pi with the below code: 我正在研究一个用以下代码计算pi的Leibniz近似的项目:

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. 但是,输出值始终为12位数。 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是否支持更精确的浮点,还是我必须使用一些外部库?

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 ). Python的float类型映射到您的平台的C编译器调用double (请参阅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 Python标准库还附带一个任意精度的十进制模块,称为decimalhttp//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). 使用Python的float,你可以得到15-17位数的精度(如果你看到更少,你可能需要在打印时使用不同的格式说明符)。

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? 请参阅Python浮点任意精度可用?

Try using Decimal . 尝试使用Decimal

Read Arbitrary-precision elementary mathematical functions (Python) original for more information 阅读任意精度基本数学函数(Python) 原始信息以获取更多信息

The Leibniz formula converges extremely slowly - honestly, you won't live long enough for it get 12 digits of accuracy. Leibniz公式非常缓慢地收敛 - 老实说,你不会活得足够长,因为它可以获得12位精度。 Click here for one way to accelerate it enormously. 点击这里获取一种极大加速的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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