求解二次公式

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)

如果有这样的帮助,还有办法吗?

Ash*_*ary 5

您得到的原因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)


mic*_*ica 5

问题在这里:

  1. 运算符优先级:您/2*a应该/(2*a)正常工作.
  2. 域名sqrt:math.sqrt负数上的保释金.
  3. 编辑2: 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存在.)


spe*_*ope 5

要处理复数,请使用 cmath。

import cmath
cmath.sqrt(negativenumber)
Run Code Online (Sandbox Code Playgroud)