Rounding floats with representation error to the closest and correct result

我只是一个虾纸丫 提交于 2019-12-01 04:11:38

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.

The python docs devote a section to it

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

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')

The real issue here is to identify how the representation error could start to be a problem in the first place.

You should not be using the representation for human-readable printing of floats, you should be using for example str.format or some other presentation method.

Keep your numbers as numbers for all calculations (whether you do that with floats or Decimals or whatever...) and only round or truncate things at presentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!