如何使用 Python 进行精确的小数计算?


在本文中,我们将学习如何在 Python 中执行精确的小数计算。

使用的方法

  • 使用 decimal 模块的 Decimal() 函数

  • 使用 math 模块的 fsum() 函数

浮点数无法精确表示所有十进制数是一个众所周知的缺点。此外,即使是简单的数学计算也会存在一些误差。例如 -

示例

以下程序展示了浮点数无法精确表示所有十进制数 -

x = 4.2
y = 3.1
 
# printing the sum of both the variables
print("x + y =", x + y)
 
# checking if the sum is both the variables is equal to 7.3
print((x + y) == 7.3)

输出

执行上述程序将生成以下输出 -

x + y = 7.300000000000001
False

这些错误是系统底层 CPU 和其浮点单元使用的 IEEE 754 算术标准的“特性”。如果您使用 float 实例编写代码,则无法防止此类错误,因为 Python 的 float 数据类型使用原生表示形式保存数据。

使用decimal 模块将以牺牲一些性能为代价获得更高的精度。让我们在下面看看。

方法 1:使用 decimal 模块的 Decimal() 函数

示例

以下程序展示了如何使用 Decimal() 函数进行精确的小数计算 -

# importing Decimal from decimal module
from decimal import Decimal
x = Decimal('4.2')
y = Decimal('3.1')
# printing the sum of both the variables
print("x + y =", x + y)
# checking if the sum is both the variables is equal to 7.3 using by passing the sum to the Decimal Function
print((x + y) == Decimal('7.3'))

输出

执行上述程序将生成以下输出 -

x + y = 7.3
True

在上面的代码中,一开始看起来可能有点奇怪,即把数字指定为字符串。但是,decimal 对象的工作方式完全符合您的预期(支持所有常见的数学运算等)。当您打印它们或在字符串格式化函数中使用它们时,它们看起来像普通的数字。

decimal的一个关键特性是能够控制计算的各个方面,例如位数和舍入。

示例

要执行此操作,请创建一个本地上下文并修改其设置。

# importing localcontext from decimal module
from decimal import localcontext
x = Decimal('2.3')
y = Decimal('2.7')
# dividing x by y(returns as a floating-point number)
print(x / y)
with localcontext() as context:
   # rounding the number upto 3 digits i.e, precision 3
   context.prec = 3
   # Dividing x by y with precision set to 3
   print(x / y)

输出

执行上述程序将生成以下输出 -

0.8518518518518518518518518519
0.852

将精度值增加到“60”以获得更高的精度

示例

# importing localcontext from decimal module
import decimal
from decimal import localcontext
x = decimal.Decimal('2.3')
y = decimal.Decimal('2.7')
# dividing x by y(returns as a floating-point number)
print(x / y)
with localcontext() as context:
   # Rounding the number upto 60 digits i.e, precision 60
   context.prec = 60
   # Dividing x by y with precision set to 3
   print(x / y)

输出

执行上述程序将生成以下输出 -

0.8518518518518518518518518519
0.851851851851851851851851851851851851851851851851851851851852

方法 2:使用 math 模块的 fsum() 函数

decimal 模块实现了 IBM 的“通用十进制算术规范”。

不用说,还有很多自定义选项超出了本文的范围。

Python 初学者可能会倾向于使用 decimal 模块来解决 float 数据类型报告的精度问题。了解您的应用领域也很重要。在处理科学或工程问题、计算机图形或大多数其他科学性质的事物时,使用普通的浮点类型更为常见。

例如,现实世界中相对较少的元素是以浮点数提供的 17 位精度来测量的。因此,即使是微小的计算误差也没有影响。原生浮点数的速度也明显更快,如果您需要运行大量计算,这一点至关重要。

示例

但是,您无法完全避免错误。数学家们已经广泛研究了许多算法,有些算法在处理错误方面比其他算法更好。此外,减法抵消和添加大数和小数等实践带来的后果需要谨慎处理。

inputList = [1.23e+18, 1, -1.23e+18]

# observe how the 1 disappears here if we perform sum() on the list
print(sum(inputList)) 

输出

执行上述程序将生成以下输出 -

0.0

fsum() 查找给定范围或可迭代对象之间的总和。它需要导入 math 库。它广泛用于数学计算。

语法

以下是函数的语法。

maths.fsum( iterable )

可迭代对象可以是范围、数组或列表。

返回值类型 -

它返回一个浮点数。

示例

以下示例可用于解决math.fsum()中更精确的实现 -

# importing math module 
import math
# input list
inputList = [1.23e+18, 1, -1.23e+18]
# adding the sum of elements of the list using the fsum() function
print(math.fsum(inputList))

输出

执行上述程序将生成以下输出 -

1.0

相反,您实际上需要研究并了解其他算法的误差传播特性。

尽管如此,处理金融等主题的程序是 decimal 模块最常使用的地方。当此类系统中的计算出现微小的不准确性时,是非常令人不快的。

因此,decimal 模块提供了一种避免这种情况的方法。当 Python 与数据库交互时,经常会再次遇到 Decimal 对象,尤其是在访问财务数据时。

结论

在本文中,我们了解了普通计算在某些情况下如何失败以及为什么需要精确的小数计算。我们学习了如何使用两个不同的函数:decimal() 和 fsum() 执行精确的小数计算。我们还学习了如何使用 localcontext() 函数设置结果的精度。

更新于: 2023年1月27日

1K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.