具有真实和复杂根的二次求解器

时间:2015-03-09 19:39:47

标签: python

我正在尝试编写一个程序,它将根据二次公式生成给定a,b和c的根。我已经做到了这一点,当它的根是真实的或当它是双根时它起作用,但我不确定当有复杂的根时如何前进。例如,如果我试图找到y = 2x ^ 2 - 5x + 17的根。有什么建议吗?这是我到目前为止所拥有的:

import math
import cmath

def quadSolver(a,b,c, tol = 1e-18):
    print('Equation: {0}x**2 + {1}x + {2}'.format(a,b,c))
    discriminant = b**2 - 4 * a * c
    if discriminant > 0:
        root1 = float(-b + math.sqrt(b**2 - 4 * a * c))/ (2 * a)
        root2 = float(-b - math.sqrt(b**2 - 4 * a * c))/ (2 * a)
        print('Has two roots:')
        print(root1)
        print(root2)
    elif discriminant == 0:
        root1 = float(-b + math.sqrt(b**2 - 4 * a * c))/ (2 * a)
        print('Has a double root:')
        print(root1)
    elif discriminant < 0:
        root1 = (-b + cmath.sqrt(b**2 - 4 * a * c))/ (2 * a)
        root2 = (-b - cmath.sqrt(b**2 - 4 * a * c))/ (2 * a)
        print('Has two complex roots:')
        print(root1)
        print(root2)

**这样可以使它现在产生复杂的根,但现在我遇到a = 0时遇到麻烦,即当y = mx + b或y =常数时。那么如何编辑它以包含那些呢?

2 个答案:

答案 0 :(得分:2)

如果您的discriminant是&lt; 0,您在计算中可能需要cmath.sqrt

>>> import cmath
>>> cmath.sqrt(-1)
1j

编辑:要回答您的第二个问题,当a == 0您的等式为线性时:bx + c = 0,其单个解是x = -c/b。 (显然,如果a==b==0你没有要解决的等式!)

未经测试,但为了给您提示:

import math
import cmath

def quadSolver(a,b,c, tol = 1e-18):
    print('Equation: {0}x**2 + {1}x + {2}'.format(a,b,c))
    if a==b==0:
        if c!=0:
            print('Not a valid equation')
        else:
            print(' 0=0 is not an interesting equation')
        return

    if a==0:
        print('Single solution is x =', -c/b)
        return

    discriminant = b**2 - 4 * a * c
    if discriminant > 0:
        root1 = (-b + math.sqrt(discriminant))/ (2 * a)
        root2 = (-b - math.sqrt(discriminant))/ (2 * a)
        print('Has two roots:')
        print(root1)
        print(root2)
    elif discriminant == 0:
        root1 = float(-b + math.sqrt(discriminant))/ (2 * a)
        print('Has a double root:')
        print(root1)
    elif discriminant < 0:
        root1 = (-b + cmath.sqrt(discriminant))/ (2 * a)
        root2 = (-b - cmath.sqrt(discriminant))/ (2 * a)
        print('Has two complex roots:')
        print(root1)
        print(root2)

(注意,因为您定义了discriminant,您可以在后续计算中使用它。)

答案 1 :(得分:0)

import math
import cmath
def main():
    a=int(input("enter a: "))
    b=int(input("enter b: "))
    c=int(input("enter c: "))
    d=((math.pow(b,2))-(4*a*c))
    if a!=0:
        if d>0:
           x1=(-b+math.sqrt(d))/(2*a)
           x2=(-b-math.sqrt(d))/(2*a)
           print("x1=",x1," and x2=",x2)
           print("real root")
        elif d==0:
           x=-b/(2*a)
           print("x=",x)
           print("equal root" )
        elif d<0:
            x1=(-b+cmath.sqrt(d))/(2*a)
            x2=(-b-cmath.sqrt(d))/(2*a)
            print("x1=",x1," and x2=",x2)
            print("complex root")
    else:
        print("this is not quadratic equation")
main()
########albany.cs######
相关问题