Python 小数模块帮助我们以适当的精度进行除法和四舍五入numbers.
In this lesson on decimal module in Python, we will see how we can manage decimal numbers in our programs for precision and formatting and making calculations as well. The precision with decimal numbers is very easy to lose if numbers are not handled correctly. Let’s see how the decimal module and its available functions help in these areas.
十进制数只是具有固定小数点的浮点数。我们必须根据需要正确舍入数字,否则结果可能会出乎意料。 Python 的十进制模块帮助我们更精确地处理十进制数。
在实际使用这个模块之前,让我们看看我们正在谈论什么精度,并确定为什么我们实际上需要这个模块。看下面的代码片段:
division = 72 / 7
print(division)
Let’s see the output for this program: Well, the answer was not actually accurate and there were no decimal points at all! Let’s see how we can correct this by using the decimal module.
在我们在这篇文章中制作的所有程序中,我们将在所有程序中导入十进制模块:
import decimal
可能的情况是我们只从这个模块导入一个特定的函数。这可以这样做:
from decimal import Decimal
让我们开始将十进制模块放入一些程序中。
我们现在将从与该模块相关的示例开始。
在这里,我们将更正上面编写的程序以执行应产生浮点结果的除法。使用十进制模块修改后的程序将如下所示:
import decimal
division = decimal.Decimal(72) / decimal.Decimal(7)
print(division)
Let’s see the output for this program: To notice, the division is correct now and precise as well, or maybe it is too precise?
在上一个程序中,现在答案中有 25 位小数。但是,如果我们只需要最多三位小数值怎么办?这也是可以控制的。在这里,我们将控制答案的精度,这不会反映在我们程序中的其他操作中:
import decimal
with decimal.localcontext() as ctx:
ctx.prec = 3
division = decimal.Decimal(72) / decimal.Decimal(7)
print(division)
again = decimal.Decimal(72) / decimal.Decimal(7)
print(again)
We did the division operation two times to prove a point. Let’s see the output for this program: Noticed something? The precision we set was only valid for a single time. Next time we did the division, we got back the same result.
还可以在程序中全局控制精度。当您在程序中处理大量数字时,并不建议始终这样做。这是一个例子:
import decimal
decimal.getcontext().prec = 3
division = decimal.Decimal(72) / decimal.Decimal(7)
print(division)
again = decimal.Decimal(72) / decimal.Decimal(7)
print(again)
Let’s see the output for this program:
可以使用以下命令对数字进行优雅地舍入round(...)
功能。让我们尝试一下:
import decimal
#Can be rounded to 13.48 or 13.49
rounded = round(13.485, 2)
print(rounded)
Let’s see the output for this program: The number in program can be rounded to 13.48 or 13.49. By default, the round(...)
function rounds down. This can be changed as well:
import decimal
#Can be rounded to 13.48 or 13.49
rounded = round(13.485, 2)
print(decimal.Decimal(rounded).quantize(decimal.Decimal('0.00'), rounding=decimal.ROUND_UP))
Let’s see the output for this program:
如果您有兴趣查看十进制模块默认设置的默认上下文,可以使用以下脚本:
from decimal import *
print(getcontext())
Let’s see the output for this program: That’s all for python decimal module, it’s very useful when working with float point numbers.