本文介绍了“圆形"行为Python中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能给我解释一下这段代码:

>>>回合(0.45, 1)0.5>>>回合(1.45, 1)1.4>>>回合(2.45, 1)2.5>>>回合(3.45, 1)3.5>>>回合(4.45, 1)4.5>>>回合(5.45, 1)5.5>>>回合(6.45, 1)6.5>>>回合(7.45, 1)7.5>>>回合(8.45, 1)8.4>>>回合(9.45, 1)9.4

更新

我猜是因为浮动表示.我说得对吗?

解决方案

你说得对.没有一个数字可以准确表示.在某些情况下,小数部分严格大于 0.45,在某些情况下严格小于:

In [4]: ['%.20f' % val for val in (0.45, 1.45, 2.45, 3.45, 4.45, 5.45, 6.45, 7.45, 8.45, 9.45)]出[4]:['0.45000000000000001110','1.44999999999999995559','2.45000000000000017764','3.45000000000000017764','4.45000000000000017764','5.45000000000000017764','6.45000000000000017764','7.45000000000000017764','8.44999999999999928946','9.44999999999999928946']

这解释了看似不一致的舍入.

Could anyone explain me this pice of code:

>>> round(0.45, 1)
0.5
>>> round(1.45, 1)
1.4
>>> round(2.45, 1)
2.5
>>> round(3.45, 1)
3.5
>>> round(4.45, 1)
4.5
>>> round(5.45, 1)
5.5
>>> round(6.45, 1)
6.5
>>> round(7.45, 1)
7.5
>>> round(8.45, 1)
8.4
>>> round(9.45, 1)
9.4

Updated

I guess it is because of floating representation. Am I right?

解决方案

You are right. None of the numbers can be represented exactly. In some cases the fractional part is strictly greater than 0.45 and in some it is strictly less:

In [4]: ['%.20f' % val for val in (0.45, 1.45, 2.45, 3.45, 4.45, 5.45, 6.45, 7.45, 8.45, 9.45)]
Out[4]: 
['0.45000000000000001110',
 '1.44999999999999995559',
 '2.45000000000000017764',
 '3.45000000000000017764',
 '4.45000000000000017764',
 '5.45000000000000017764',
 '6.45000000000000017764',
 '7.45000000000000017764',
 '8.44999999999999928946',
 '9.44999999999999928946']

This explains the seemingly inconsistent rounding.

这篇关于“圆形"行为Python中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 00:40