我正在写一个使用二次公式求解二次方程的程序,但它只在a=1时有效,但我希望它在a大于1时有效
下面是我的代码:
import math
def solve(a, b, c):
x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
print "x = %s" %x
print "or"
y = ((-1)* b - math.sqrt(b**2-4*a*c))/2*a
print "x = %s" %x
while 1:
a = int(raw_input("Enter A :"))
b = int(raw_input("Enter B :"))
c = int(raw_input("Enter C :"))
solve(a, b, c)它适用于1,但是当我使用一个大于1的数字时,比如使用4,我会得到这个错误
Traceback (most recent call last):
File "C:\Documents and Settings\User\Desktop\Factor.py", line 18, in <module>
solve(a, b, c)
File "C:\Documents and Settings\User\Desktop\Factor.py", line 5, in solve
x = ((-1)* b + math.sqrt(b**2-4*a*c))/2*a
ValueError: math domain error有什么办法可以解决这个问题吗?如果是的话,救命啊!
发布于 2013-05-02 14:37:54
问题就在这里:
/2*a应该为/(2*a)才能正常工作。sqrt:math.sqrt的域在负numbers./2*a>d13之后的 y = ...应为be要修复后一种情况,您需要某种条件:
disc = b**2 - 4*a*c
sqrtdisc = math.sqrt(disc) if disc >= 0 else math.sqrt(-disc)*1j编辑:您也可以使用cmath.sqrt,它会自动处理负数:
disc = b**2 - 4*a*c
sqrtdisc = cmath.sqrt(disc)(感谢其他回答者,他们有效地让我知道了cmath的存在。)
发布于 2013-05-02 14:37:18
获取ValueError的原因是表达式b**2-4*a*c返回的是负值,这对于math.sqrt是不允许的。
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<ipython-input-38-5234f21f3b4d>", line 1, in <module>
math.sqrt(-1)
ValueError: math domain error也可以使用cmath.sqrt处理负值:
>>> import cmath
>>> cmath.sqrt(-1)
1j发布于 2013-05-02 14:41:18
要处理复数,请改用cmath。
import cmath
cmath.sqrt(negativenumber)https://stackoverflow.com/questions/16331745
复制相似问题