四舍五入浮动,并带有表示错误,直到最接近和正确的结果 [英] Rounding floats with representation error to the closest and correct result

查看:112
本文介绍了四舍五入浮动,并带有表示错误,直到最接近和正确的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种经典的表示错误 Python开始成为一个问题:我需要将它们用于Numpy中的Matrix运算,并且尚不支持 decimal 类型.

I have a situation when the classic representation error in Python started to be a problem: I need them to be used for Matrix operations in Numpy and the decimal type is not supported yet.

大家都知道,如果我执行111.85 * 111.85,我会得到12510.422499999999,但是如果我执行round(12510.422499999999, 4),我会得到正确的结果,当然是12510.4225.

You all know that if I do 111.85 * 111.85 I will get 12510.422499999999 but if I round(12510.422499999999, 4) I can get the proper result which is of course 12510.4225.

但是实际问题是:

  • 这回合是个好主意和好的做法吗?
  • 在所有情况下都可以使用吗?有时小数点位置在..999小数点可能会更多的位置
  • 最后,如何为所有可能的值获取适当的小数位数以与舍入一起使用?

推荐答案

即使将数字四舍五入,小数位数也不会准确地符合您的期望. Python可能仅显示最高有效位,但是潜在的十进制不准确度仍然存在.

Even if you round the number, the decimal still won't be exactly what you expect it to be. Python may display only the most significant bits, but the underlying decimal inaccuracy is still there.

python文档专门介绍了一个部分

由于方式不同,许多用户不了解近似值 显示值. Python仅输出十进制近似值 二进制存储的二进制近似值的真实十进制值 机器.在大多数机器上,如果Python要打印真实的十进制数 二进制近似值存储为0.1,则必须 显示

Many users are not aware of the approximation because of the way values are displayed. Python only prints a decimal approximation to the true decimal value of the binary approximation stored by the machine. On most machines, if Python were to print the true decimal value of the binary approximation stored for 0.1, it would have to display

>>> 0.1
0.1000000000000000055511151231257827021181583404541015625

这个数字比大多数人认为有用的多,因此Python保留了 通过显示取整值可以代替的数字位数

That is more digits than most people find useful, so Python keeps the number of digits manageable by displaying a rounded value instead

>>> 1 / 10
0.1

对于大多数用例,可以安全地忽略不准确性.如果你是 处理极小或非常大的数字或需求 精度精确到小数点后一位,您可以使用十进制 图书馆

For most use cases, the inaccuracy can safely be ignored. If you are dealing with extremely small or extremely large numbers or need accuracy out to many decimal places, you can use the decimal library

 >>> Decimal('111.85') * Decimal('111.85')
 Decimal('12510.4225')

这篇关于四舍五入浮动,并带有表示错误,直到最接近和正确的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆