Python实现一元二次方程求根

“公式法”是一般方法,只要明确了二次项系数、一次项系数及常数项,若方

程有实根,就一定可以用求根公式求出根,但因为要代入


求值,所以对某些特殊方程,解法又显得复杂了。

show me your code:

import math

def fix(a,b,c):

    if not isinstance(a,(int,float)):

        raise TypeError('a is not number')

    if not isinstance(b,(int,float)):

        raise TypeError('b is not number')

    if not isinstance(c,(int,float)):

        raise TypeError('c is not number')

    d = math.pow(b,2)-4*a*c

    if a == 0:

        if b == 0:

            if c == 0:

                return'方法为全体实数'

            else:

                return '方法无根'

        else:

            x1 = c/b

            x2= x1

            return x1,x2

    else:

        if d < 0:

            return '方法无根'

        else:

            x1 = (-b+math.sqrt(d))/2/a

            x2 = (-b-math.sqrt(d))/2/a

            return x1,x2

print(fix(0,0,0))

print(fix(2,3,1))

print(fix(1,3,-4))

print(fix(0,0,-4))

print(fix(0,0,4))

print(fix(3,1,4))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容