在Python中舍入 [英] Rounding in Python

查看:152
本文介绍了在Python中舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

round(1.4 999 999 999 999 999)(不含空格)四舍五入为2
,但
round (1.4 99 999 999 999 999)(不包括空格)四舍五入为1



我想这与不精确的浮点表示法,但不明白它是如何来的第一个表示被解释为接近2比1.解决方案

1.4 999 999 999 999 999 在分析时恰好是1.5,它们之间的差别太小而不能代表这个量级。



但是 1.4 99 999 999 999 999 足够低,可以解析为小于1.5,实际上1.4999999999999988897769753748434595763683319091796875,明显小于1.5

$ b

round(1.4 999 999 999 999 999) (without the spaces) gets rounded to 2 but round(1.4 99 999 999 999 999) (without the spaces) gets rounded to 1.

I suppose this has to do with imprecise floating point representations, but fail to understand how does it come that the first representation is interpreted as closer to 2 than to 1.

解决方案

Because 1.4 999 999 999 999 999 when parsed is exactly 1.5, the difference between them is too small to represent at that magnitude.

But 1.4 99 999 999 999 999 is low enough to parse to "less than 1.5", actually 1.4999999999999988897769753748434595763683319091796875, which is clearly less than 1.5

这篇关于在Python中舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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