Python舍入问题 [英] Python rounding issue

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

问题描述

我在 python 中遇到了一个非常奇怪的问题.(使用 python 2.4.x)

在窗口中:

<预><代码>>>>一 = 2292.5>>>打印 '%.0f' % a2293

但是在 Solaris 中:

<预><代码>>>>一 = 2292.5>>>打印 '%.0f' % a2292

但这在 windows 和 solaris 中都是一样的:

<预><代码>>>>一 = 1.5>>>打印 '%.0f' % a2

有人可以解释这种行为吗?我猜它的平台依赖于 python 的编译方式?

解决方案

最终负责执行格式化的函数是 PyOS_snprintf(请参阅来源).正如您所猜测的那样,不幸的是,这依赖于系统,即它依赖于 vsprintfvsnprintf 或其他最终由平台的 C 运行时库提供的类似函数(我不不记得 C 标准是否对浮点数的 '%f' 格式有任何说明,这些浮点数恰好处于两个可能的舍入值之间的中间"......但是,C 标准是否对此松懈,或者 C 标准是否严格但一些 C 运行时破坏了它,最终是一个相当学术的问题......).

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?

解决方案

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

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

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