Ser*_*ial 0 python math quadratic equation-solving
我正在编写一个程序来使用二次方程式求解二次方程,但它仅在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)
Run Code Online (Sandbox Code Playgroud)
它适用于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
Run Code Online (Sandbox Code Playgroud)
如果有这样的帮助,还有办法吗?
您得到的原因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
Run Code Online (Sandbox Code Playgroud)
也用于cmath.sqrt处理负值:
>>> import cmath
>>> cmath.sqrt(-1)
1j
Run Code Online (Sandbox Code Playgroud)
问题在这里:
/2*a应该/(2*a)正常工作.sqrt:math.sqrt负数上的保释金.y = ...刚刚print "or"应该是x = ...要修复后者,你需要某种条件:
disc = b**2 - 4*a*c
sqrtdisc = math.sqrt(disc) if disc >= 0 else math.sqrt(-disc)*1j
Run Code Online (Sandbox Code Playgroud)
编辑:您也可以使用cmath.sqrt,它会自动处理负数:
disc = b**2 - 4*a*c
sqrtdisc = cmath.sqrt(disc)
Run Code Online (Sandbox Code Playgroud)
(感谢各种其他回答者有效地让我知道cmath存在.)
| 归档时间: |
|
| 查看次数: |
6452 次 |
| 最近记录: |