Skip to main content
 首页 » 编程设计

python之Math.sqrt(-1) 没有错误

2025年05月04日13zhujiabin

查看下面的代码,当我输入一个负数时,似乎没有错误,但是平方根不能为负数,所以我不知道为什么会这样。

import math 
d=[] 
while True: 
    z=int(raw_input()) 
    if (z>0 and math.sqrt(z)): d.append(int(z)) 

空闲时:

math.sqrt(int(-1)) 
 
Traceback (most recent call last): 
  File "<pyshell#16>", line 1, in <module> 
    math.sqrt(int(-1)) 
ValueError: math domain error 

请您参考如下方法:

    if (z>0 and math.sqrt(z)): ... 

Boolean operations short-circuit .这意味着如果 z > 0 为假,则不会评估 math.sqrt(z)。因此没有错误。

附言严格来说,负数的平方根是存在的,并且是complex .像 scipy.sqrt() 这样的函数会很高兴地返回一个复杂的平方根:

>>> import scipy as sp 
>>> sp.sqrt(-1) 
1j