python实现解一元二次方程

python实现一元二次方程的求解

要考虑的点:

1、二元方程组a=0的情况

2、判别式是否大于0

3、当有复数解时如何表示

程序块:

# -*- coding: utf-8 -*-

import math

def root_of_square(a,b,c):
    '''solve the quadratic equation'''
    discr=pow(b,2)-4*a*c
    if a!=0 and  discr>0:
        x1=(-b+math.sqrt(discr))/(2*a)
        x2=(-b-math.sqrt(discr))/(2*a)
        return x1,x2
    elif a!=0 and discr==0:
        return -b/(2*a)
    elif a!=0 and discr<0:
        x1=str(-b/(2*a))+"+"+str(math.sqrt(-discr)/(2*a))+"i"
        x2=str(-b/(2*a))+"-"+str(math.sqrt(-discr)/(2*a))+"i"
        return x1,x2
    elif a==0 and b!=0:
        return -c/b
    else:
        return "no solution"

if __name__=="__main__":
    a=input()
    b=input()
    c=input()
    print(root_of_square(float(a),float(b),float(c)))

实验结果:

有两个不同根的情况:

输入:

1

0

-1

输出
(1.0, -1.0)

有两个同根的情况:

输入:

1

2

1

输出:
-1.0

有两个虚根的情况:

输入:

1

2

2

输出:
('-1.0+1.0i', '-1.0-1.0i')

a=0的情况:

输入:

0

1

1

输出:
-1.0

无解的情况:

输入:

0

0

1

输出:
no solution

你可能感兴趣的:(python入门)