0

我正在编写一个程序来使用二次公式求解二次方程,但它仅在 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,但是当我使用说 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

如果有帮助,有没有办法解决这个问题!

4

5 回答 5

6

问题在这里:

  1. 运算符优先级:您/2*a应该/(2*a)正常工作。
  2. 的域sqrtmath.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

编辑:您也可以使用cmath.sqrt,它会自动处理负数:

disc = b**2 - 4*a*c
sqrtdisc = cmath.sqrt(disc)

(感谢其他各种回答者有效地让我知道cmath存在。)

于 2013-05-02T06:37:54.017 回答
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

也用于cmath.sqrt处理负值:

>>> import cmath
>>> cmath.sqrt(-1)
1j
于 2013-05-02T06:37:18.097 回答
5

要处理复数,请改用 cmath。

import cmath
cmath.sqrt(negativenumber)
于 2013-05-02T06:41:17.983 回答
3

你得到 a 是math domain error因为你给了一个负值math.sqrt。这很可能在您增加时发生,因为您增加a的幅度b不足以产生b**2-4*a*c正值。

于 2013-05-02T06:37:00.387 回答
0

尝试使用这样的东西来扎根:

def roots(a, b, c):

    def getDiscriminant(a, b, c,Error = "Imaginary Roots"):
        try:
            return (b ** 2 - (4 * a * c)) ** .5
        except:
            return Error

    D = getDiscriminant(a, b, c) 

    if D == False:
        return False

    b = -b
    a = 2 * a

    firstroot = float((b + D) / float(a))
    secondroot = float((b - D) / float(a))

    return (firstroot,secondroot)
于 2013-05-12T20:35:39.323 回答