将 float(“inf”) 向后移植到 Python 2.4 和 2.5
我正在将我的项目从 Python 2.6 向后移植到 Python 2.4 和 2.5。在我的项目中我使用了float("inf")
,现在我发现它在Python 2.5上不可用。它有向后移植吗?
I'm backporting my project from Python 2.6 to Python 2.4 and 2.5. In my project I used float("inf")
, and now I find it is unavailable on Python 2.5. Is there a backport of it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
无论是长拼写还是短拼写对我来说都很好:
-c
标志意味着“将以下参数作为 Python 命令执行”。PEP754 (被拒绝)确实提到了有关特殊 IEEE-754 的问题价值观。它建议使用类似
1e300000
的东西来生成浮点溢出并创建inf
,但它确实指出这很丑陋并且不能保证可移植。Spelling it either the long way or the short way works fine for me:
The
-c
flag means "execute the following arguments as a Python command."PEP754 (which was rejected) does mention your issue about special IEEE-754 values. It suggests using something like
1e300000
to generate a floating point overflow and createinf
, but it does note that this is ugly and not guaranteed to be portable.你应该能够通过给Python一个足够大的浮点常量来伪造它。例如:
You should be able to fake it up by giving Python a sufficiently large floating point constant instead. For instance:
decimal 模块自 Python 2.4 起可用,支持正或负无限小数。它的行为并不总是像浮点数(例如,添加小数,并且不支持浮点数),但进行正确的比较,这对我来说已经足够好了。
The decimal module is available since Python 2.4 and supports positive or negative infinite decimals. It does not always behave like a float (eg. adding a decimal and a float is not supported) but does the right thing for comparison, which was good enough for me.
我创建了一个反向移植,在 Python 2.5+ 上进行了测试,可能可以轻松地在 Python 2.4 上工作:
https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/infinity.py
I created a backport, tested on Python 2.5+, can probably be easily made to work on Python 2.4:
https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/infinity.py
借用 NumPy 几行:
这里,
inf
是一个 常规 pythonfloat
,因此您无需再为 NumPy 烦恼。Borrowing NumPy for a few lines:
Here,
inf
is a regular pythonfloat
, so you don't need to bother with NumPy any further.