美文网首页人生苦短 我用Python
Python实现一元二次方程求根

Python实现一元二次方程求根

作者: 直到世界的尽头_yifan | 来源:发表于2017-12-17 17:54 被阅读0次

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

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

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

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))

相关文章

网友评论

    本文标题:Python实现一元二次方程求根

    本文链接:https://www.haomeiwen.com/subject/qacuwxtx.html