Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 既然我们有round()函数,为什么还要麻烦量化一个浮点数呢?_Python_Floating Point_Decimal - Fatal编程技术网

Python 既然我们有round()函数,为什么还要麻烦量化一个浮点数呢?

Python 既然我们有round()函数,为什么还要麻烦量化一个浮点数呢?,python,floating-point,decimal,Python,Floating Point,Decimal,我在一本Python书籍中读到,在金融界,有时最好使用quantize()和decimal模块来舍入浮点数。书中给出了如下示例: from decimal import Decimal price = Decimal('19.99') tax = Decimal('0.06') total = price + (price * tax) penny = Decimal('0.01') total.quantize(penny) 但为什么不呢 round(19.99+19.99*0.06,2)

我在一本Python书籍中读到,在金融界,有时最好使用quantize()和decimal模块来舍入浮点数。书中给出了如下示例:

from decimal import Decimal
price = Decimal('19.99')
tax = Decimal('0.06')
total = price + (price * tax) 
penny = Decimal('0.01')
total.quantize(penny)
但为什么不呢

round(19.99+19.99*0.06,2)
?


quantize()在数值精度方面何时优于round()?任何人都可以举个例子吗?

我不认为使用十进制(和量化)的主要原因是速度:精度。从文档中:

十进制数字可以精确表示。相反,像1.1和2.2这样的数字在二进制浮点中没有精确的表示。最终用户通常不希望1.1+2.2显示为3.30000000000000003,因为它使用二进制浮点


如果您处理的是大数字,并且您要求结果的正确率高达1%,那么精度(使用浮点算术)可能是一个问题。

我不认为使用十进制(和量化)的主要原因是速度:精度。从文档中:

十进制数字可以精确表示。相反,像1.1和2.2这样的数字在二进制浮点中没有精确的表示。最终用户通常不希望1.1+2.2显示为3.30000000000000003,因为它使用二进制浮点

如果您处理的是大数字,并且要求结果的正确率高达1%,那么(使用浮点算术)的准确性可能会有问题