我对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我在纸上做了这个问题,得到了两个答案.
发布于 2015-01-30 10:54:54
如果您得到了答案,它一定是一个复数(在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,因为这样做(这将需要importing cmath在您的程序开始时)。
使用cmath,我得到了以下结果:
Problem #5
Root 1: 1.1401754250991378j
Root 2: 1.1401754250991378j(其中j是-1的平方根)。
https://stackoverflow.com/questions/28232673
复制相似问题