纯粹是出于好奇,但为什么会这样呢?
>>> a = float('Nan')
>>> a**2.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: (33, 'Domain error')
我原以为它只是简单地返回NaN而不是生成错误。
答案 0 :(得分:4)
它看起来像你正在使用的Python的任何实现中的错误。它在我测试的所有Python版本中都按预期工作,范围从2.5到3.1。
>>> nan = float('NaN')
>>> nan ** 2.0
nan
答案 1 :(得分:4)
从http://www.mail-archive.com/relax-devel@gna.org/msg00337.html开始,由于编译器如何实现浮点内容,似乎这只是Windows构建的情况。
实施例
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> float('NaN')
nan
>>> _**2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: (33, 'Domain error')
答案 2 :(得分:1)
在Vista SP2 Intel DualCore 2.1 GHz上
CPython的:
In []: sys.version
Out[]: '2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]'
In []: float('NaN')** 2.
Out[]: nan
>>> sys.version
'3.1.3 (r313:86834, Nov 27 2010, 18:30:53) [MSC v.1500 32 bit (Intel)]'
>>> float('NaN')** 2.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: (33, 'Domain error')
相同的编译器,但版本不同,结果不同
来自不同的世界,IronPython:
>>> sys.version
'2.6.1 ()'
>>> float('NaN')** 2.
nan
>>> sys.version
'2.7.0 (IronPython 2.7 Beta 1 (2.7.0.10) on .NET 4.0.30319.1)'
>>> float('NaN')** 2.
nan
答案 3 :(得分:0)
这就是我得到的
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
>>> nan=float("NaN")
>>> nan
nan
>>> nan*2
nan
>>> nan**2
nan
>>>