ValueError:数学域错误 – 二次方程(Python)

我是
python编程和这个网站的新手.我目前正在研究一个问题,似乎无法理解错误.

import math
# Problem number 5.
A5 = 5
B5 = 0
C5 = 6.5
# Root1
x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
# Root2
x10 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
# Print solution
print()
print('Problem #5')
print('Root 1: ',x9)
print('Root 2: ',x10)

运行后我得到了这个:

    x9 = (-B5 + math.sqrt(B5**2 - 4*A5*C5))/(2*A5)
ValueError: math domain error

我在纸上做了这个问题,得到了两个答案……

最佳答案 如果你得到了答案,它必须是一个复数(默认情况下不包含在Python中).看看math.sqrt行(B5 ** 2 – 4 * A5 * C5).

这样评估如下:

math.sqrt(B5**2 - 4*A5*C5)
math.sqrt(0**2 - 4*5*6.5)
math.sqrt(0 - 130)
math.sqrt(-130)

函数math.sqrt找不到复杂的根.您应该使用cmath.sqrt,因为这样做(这将需要在程序开始时导入cmath).

使用cmath,我得到这个结果:

Problem #5
Root 1:  1.1401754250991378j
Root 2:  1.1401754250991378j

(其中j是-1的平方根).

点赞