p y t h o n 解 决 a x 2 + b x + c = 0 python解决 ax^2 + bx + c = 0 python解决ax2+bx+c=0
使用IDE为PyCharm
首先是添加numpy包
操作如下
第一步 File ->settings
第二步 project ->project interpreter 再点击右边+
第三步
第四步 等待安装完毕即可
说明
numpy的sqrt可以对正负数进行开方 ,可以处理ax^2+bx+c=0的所有情况,即sqrt 对实数、复数统一处理
实现代码如下
from numpy.lib.scimath import sqrt
a = int(input())
b = int(input())
c = int(input())
if a == 0:
if b == 0 and c ==0:
print("There are infinitely many solutions!")
else:
if b==0:
print ("There is no solution")
else:
print("There is a unique solution x=%g" %(-1*c/b))
else:
disc = b*b -4*a*c
if disc > 0:
x1 = (-b + sqrt(disc)) / 2 / a
x2 = (-b - sqrt(disc)) / 2 / a
if disc > 0:
print("There are two distinct real roots x1=%g and x2=%g" % (x1, x2))
else:
print("There are two conjugate roots x1=%g and x2=%g" % (x1, x2))
else:
if disc == 0:
print("There are two equal real roots x1=x2=%g" % (-1 * b / 2 / a))
else:
x1 = (-b + sqrt(disc)) / 2 / a
x2 = (-b - sqrt(disc)) / 2 / a
print("There are two conjugate roots x1=%s and x2=%s" % (x1, x2))