Modulo为您提供了rest一个部门。3.5除以0.1你应该给你35剩下的0。但由于浮点数基于2的幂,数字并不准确,你会得到四舍五入的错误。
如果您需要精确划分十进制数,请使用十进制模块:
>>> from decimal import Decimal
>>> Decimal('3.5') / Decimal('0.1')
Decimal('35')
>>> Decimal('3.5') % Decimal('0.1')
Decimal('0.0')
当我被抨击时,我的答案误导了整个故事:
0.1 略大于 0.1
>>> '%.50f' % 0.1
'0.10000000000000000555111512312578270211815834045410'
如果你将浮动3.5除以这个数字,你几乎可以得到其余的0.1。
让我们从数字开始,0.11继续在两个1数字之间添加零,以便在保持大于的同时使其变小0.1。
>>> '%.10f' % (3.5 % 0.101)
'0.0660000000'
>>> '%.10f' % (3.5 % 0.1001)
'0.0966000000'
>>> '%.10f' % (3.5 % 0.10001)
'0.0996600000'
>>> '%.10f' % (3.5 % 0.100001)
'0.0999660000'
>>> '%.10f' % (3.5 % 0.1000001)
'0.0999966000'
>>> '%.10f' % (3.5 % 0.10000001)
'0.0999996600'
>>> '%.10f' % (3.5 % 0.100000001)
'0.0999999660'
>>> '%.10f' % (3.5 % 0.1000000001)
'0.0999999966'
>>> '%.10f' % (3.5 % 0.10000000001)
'0.0999999997'
>>> '%.10f' % (3.5 % 0.100000000001)
'0.1000000000'
最后一行给出了我们最终达到的印象,0.1但更改格式字符串揭示了真实的本质:
>>> '%.20f' % (3.5 % 0.100000000001)
'0.09999999996600009156'
python的默认浮点格式根本没有显示足够的精度以便3.5 % 0.1 = 0.1和3.5 % 0.1 = 35.0。它真的是3.5 % 0.100000... = 0.999999...和3.5 / 0.100000... = 34.999999....。在分割的情况下,你甚至可以得到确切的结果,因为它34.9999...是最终的四舍五入35.0。
有趣的事实:如果您使用的数字略小于0.1并执行相同的操作,您最终会得到一个略大于的数字0:
>>> 1.0 - 0.9
0.09999999999999998
>>> 35.0 % (1.0 - 0.9)
7.771561172376096e-15
>>> '%.20f' % (35.0 % (1.0 - 0.9))
'0.00000000000000777156'
使用C ++,您甚至可以显示除了3.5浮点数0.1不是35更小的东西。
#include
#include
int main(int argc, char *argv[]) {
// double/float, rounding errors do not cancel out
std::cout << "double/float: " << std::setprecision(20) << 3.5 / 0.1f << std::endl;
// double/double, rounding errors cancel out
std::cout << "double/double: " << std::setprecision(20) << 3.5 / 0.1 << std::endl;
return 0;
}
http://ideone.com/fTNVho
在Python中3.5 / 0.1为您提供了确切的结果,35因为舍入错误相互抵消。它确实是3.5 / 0.100000... = 34.9999999...。并且34.9999...到目前为止,你最终会完全结束35。C ++程序很好地展示了这一点,因为你可以混合double和float并使用浮点数的精度。