Python 舍入问题
我在 python 中遇到了一个非常奇怪的问题。 (使用python 2.4.x)
在Windows中:
>>> a = 2292.5
>>> print '%.0f' % a
2293
但在Solaris中:
>>> a = 2292.5
>>> print '%.0f' % a
2292
但这在Windows和Solaris中都是相同的:
>>> a = 1.5
>>> print '%.0f' % a
2
有人可以解释这种行为吗?我猜它的平台依赖于 python 的编译方式?
I have come across a very strange issue in python. (Using python 2.4.x)
In windows:
>>> a = 2292.5
>>> print '%.0f' % a
2293
But in Solaris:
>>> a = 2292.5
>>> print '%.0f' % a
2292
But this is the same in both windows and solaris:
>>> a = 1.5
>>> print '%.0f' % a
2
Can someone explain this behavior? I'm guessing it's platform dependent on the way that python was compiled?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最终负责执行格式化的函数是 PyOS_snprintf
(请参阅来源)。正如您所猜测的,不幸的是,这与系统相关,即它依赖于
vsprintf
、vsnprintf
或最终由平台的 C 运行时库提供的其他类似函数(我不知道)不记得 C 标准是否对浮点数的“%f”格式有任何规定,这些浮点数“恰好位于两个可能的舍入值之间”……但是,无论 C 标准对此是否宽松,或者更确切地说 C 标准是严格的,但一些 C 运行时会破坏它,最终是一个相当学术的问题......)。The function ultimately in charge of performing that formatting is
PyOS_snprintf
(see the sources). As you surmise, that's unfortunately system-dependent, i.e., it relies on
vsprintf
,vsnprintf
or other similar functions that are ultimately supplied by the platform's C runtime library (I don't recall if the C standard says anything about the '%f' formatting for floats that are "exactly midway" between two possible rounded values... but, whether the C standard is lax about this, or rather the C standard is strict but some C runtimes break it, ultimately is a pretty academic issue...).round() 向最接近的偶数舍入
“%n.nf”的工作方式与 round() 相同
int() 向零截断
“将正数四舍五入到最接近的整数
可以通过加0.5截断来实现”
-- http://en.wikipedia.org/wiki/Rounding
在Python中你可以这样做其内容为:
math.trunc( n + 0.5 )
当然假设 n 是正数...
如果“四舍五入到偶数”不合适,我现在使用
math.trunc( n + 0.5 )
我曾经使用int(round(n))
round() rounds toward the nearest even integer
"%n.nf" works the same way as round()
int() truncates towards zero
"rounding a positive number to the nearest integer
can be implemented by adding 0.5 and truncating"
-- http://en.wikipedia.org/wiki/Rounding
In Python you can do this with:
math.trunc( n + 0.5 )
assuming n is positive of course...
Where "round half to even" is not appropriate, i now use
math.trunc( n + 0.5 )
where i used to useint(round(n))
I 依赖于平台。您可以在此处找到文档。
使用 ceil 或 floor 当您知道自己想要什么时(向上或向下舍入)。
I is plataform dependent. You can find the documentation here.
It is good to user ceil or floor when you know what you want (to round up or down).