开发者

Python NaN squared error

开发者 https://www.devze.com 2023-02-07 16:51 出处:网络
This is purely out of curiosity, but why does this occur? &开发者_运维问答gt;>> a = float(\'Nan\')

This is purely out of curiosity, but why does this occur?

&开发者_运维问答gt;>> a = float('Nan')
>>> a**2.0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: (33, 'Domain error')

I would have expected it to simply return NaN instead of generating an error.


From http://www.mail-archive.com/relax-devel@gna.org/msg00337.html, it seems that this is only the case on the windows builds, due to how the compiler implements floating point stuff.

  • Would some of the people who can't reproduce post their OS?
  • Would someone having a 2.x on windows installed try it out (I get the same error on 3.1.3 (on Windows 7 32 bit))?
  • @OP: You are using windows, yes?

Example

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


It looks like a bug in whatever implementation of Python you are using. It works as expected for me in all Python versions I tested, ranging from 2.5 to 3.1.

>>> nan = float('NaN')
>>> nan ** 2.0
nan
  • Python 2.6.4 on ideone
  • Python 3.1.2 on ideone


On 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')

Same compiler, but different versions, different results

From different world, 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


This is what I get

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
>>>
0

精彩评论

暂无评论...
验证码 换一张
取 消