Skip to main content
 首页 » 编程设计

python之二次根函数中的数学域错误

2025年05月04日14xiaohuochai

我的代码:

def root1(a,b,c): 
    return (-b+sqrt((b**2)-4*a*c))/2*a 
def root2(a,b,c): 
    return (-b-sqrt((b**2)-4*a*c))/2*a 

我遇到了一个ValueError: math domain error,我不知道为什么。

请您参考如下方法:

大概你有类似的东西

from math import sqrt 

代替导入,使用

from cmath import sqrt 

cmath 中的sqrt 函数可以处理否定参数。

例如,

>>> from math import sqrt 
>>> sqrt(-4) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
ValueError: math domain error 
 
>>> from cmath import sqrt 
>>> sqrt(-4) 
2j