提高 Python 中的浮点精度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21079282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increasing floating point precision in Python
提问by hkk
I was working on a project to compute the Leibniz approximation for pi with the below code:
我正在研究一个项目,使用以下代码计算 pi 的莱布尼茨近似值:
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?
但是,输出值始终为 12 位数字。如何提高计算的精度(例如更多位数)?Python 是否支持更精确的浮点数,还是必须使用一些外部库?
采纳答案by albusshin
Try using Decimal.
尝试使用Decimal.
Read Arbitrary-precision elementary mathematical functions (Python)originalfor more information
阅读任意精度初等数学函数 (Python)原版以获取更多信息
回答by NPE
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 的浮点数,您可以获得 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.
如果您需要更多,则需要使用不同的方法(仅使用整数算术的方法)或不同的方法来表示浮点数。
回答by Max Noel
Python's floattype 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 标准库还带有一个任意精度的十进制模块,称为decimal:http: //docs.python.org/2/library/decimal.html
回答by Tim Peters
The Leibniz formula converges extremely slowly - honestly, you won't live long enough for it get 12 digits of accuracy. Click herefor one way to accelerate it enormously.
莱布尼茨公式的收敛速度非常慢——老实说,你活不了多久,它会得到 12 位数的准确度。 单击此处了解一种极大地加速它的方法。

