卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16333本站已运行3317

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

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

在本文中,我们将学习如何在Python中进行准确的十进制计算。

使用的方法

  • Using the Decimal() function of the decimal Module

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

浮点数无法准确表示所有十进制数是众所周知的缺点。此外,即使是简单的数学计算也会产生一些错误。例如 −

Example

以下程序展示了浮点整数无法准确表示所有十进制数的能力-

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数据类型使用本机表示来保存数据。

Using the decimal module will give you greater accuracy at the cost of some performance. Let us see it below.

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

Example

以下程序展示了使用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的关键特性。

Example

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

# 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'以获得更高的准确性

Example

# 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()函数

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

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

Python初学者可能会被诱导使用decimal模块来解决浮点数据类型的精度问题。但也需要了解你的应用领域。在处理科学或工程问题、计算机图形或其他科学性质的事物时,通常更常用普通浮点数类型。

例如,实际世界中很少有元素能够以浮点数提供的17位精度进行测量。因此,即使是微小的计算误差也没有影响。而且,原生浮点数的速度也明显更快,这对于需要运行大量计算的情况至关重要。

Example

然而,你无法完全避免错误。许多算法已经被数学家广泛研究,其中一些在处理错误方面比其他算法更好。此外,由于减法抵消和加法大数和小数的做法可能导致一些后果,需要一些谨慎。

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 )

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

返回类型 -

它返回一个浮点数。

Example

下面的示例可以用于在 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模块提供了一种避免这种情况的方法。当Python与数据库进行交互时,经常会再次遇到Decimal对象,特别是在访问金融数据时。

结论

我们在本文中了解到,在特定情况下,常规计算会失败,所以我们需要正确的小数计算。我们学习了如何使用两个独立的函数decimal()和fsum()进行准确的小数计算。我们还学习了如何使用localcontext()函数来设置结果的精度。

卓越飞翔博客
上一篇: 如何在Linux上编译和执行C#程序?
下一篇: PHP如何删除数据库一条记录
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏