[英]How to correctly deal with floating point arithmetic in Python?
How to correctly add or subtract using floats? 如何使用浮点数正确加减? For example how to perform: 例如如何执行:
2.4e-07 - 1e-8
so that it returns 2.3e-7
instead of 2.2999999999999997e-07
. 因此它返回2.3e-7
而不是2.2999999999999997e-07
。
Converting to int first yields unexpected results, the below returns 2.2e-07
: 首先转换为int会产生意外结果,以下返回2.2e-07
:
int(2.4e-07 * 1e8 - 1) * 1e-8
Similarly, 同样的,
(2.4e-07 * 1e8 - 1) * 1e-8
returns 2.2999999999999997e-07
. 返回2.2999999999999997e-07
。
How to perform subtraction and addition of numbers with 8 decimal point precision? 如何以8位小数点精度执行数字的减法和加法运算?
2.2999999999999997e-07
is not sufficient as the number is used as a lookup in a dictionary, and the key is 2.3e-7
. 2.2999999999999997e-07
不够,因为该数字用作字典中的查找,并且键为2.3e-7
。 This means that any value other than 2.3e-7
results in an incorrect lookup. 这意味着除2.3e-7
以外的任何值都将导致错误的查找。
It's really just a way of skirting around the issue of floating point arithmetic, but I suggest using the decimal
package from the standard library. 实际上,这只是规避浮点算术问题的一种方法,但是我建议使用标准库中的decimal
包。 It lets you do exact floating point math. 它使您可以进行精确的浮点数学运算。
Using your example, 用你的例子,
$ from decimal import Decimal
$ x = Decimal('2.4e-7')
$ y = Decimal('1e-8')
$ x-y
Decimal('2.3E-7')
It's worth noting that Decimal
objects are different than the float
built-in, but they are mostly interchangeable. 值得注意的是, Decimal
对象与内置的float
不同,但是它们大多数都是可互换的。
I suggest using the decimal
data type (it is present in the stardard installation of Python), because it uses fixed precision to avoid just the differences you are talking about. 我建议使用decimal
数据类型(它存在于Python的stardard安装中),因为它使用固定精度来避免您在谈论的差异。
>>> from decimal import Decimal
>>> x = Decimal('2.4e-7')
>>> x
Decimal('2.4E-7')
>>> y = Decimal('1e-8')
>>> y
Decimal('1E-8')
>>> x - y
Decimal('2.3E-7')
I do not know if it is what you are looking for but you can try that kind of thing: 我不知道这是否是您要寻找的东西,但是您可以尝试这种事情:
a = 0.555555555
a = float("{0:.2f}".format(a))
>>> 0.56
I hope it will help you! 希望对您有帮助!
Adrien 阿德里安
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.