如何使用Python进行准确的小数计算?
在本文中,我们将学习如何在Python中进行准确的十进制计算。
使用的方法
Using the Decimal() function of the decimal Module
使用math模块的fsum()函数
浮点数无法准确表示所有十进制数是众所周知的缺点。此外,即使是简单的数学计算也会产生一些错误。例如 −
Example
以下程序展示了浮点整数无法准确表示所有十进制数的能力-
x = 4.2 y = 3.1 1. printing the sum of both the variables print("x + y =", x + y) 1. checking if the sum is both the variables is equal to 7.3 print((x + y) == 7.3) 登录后复制