资源简介
使用python编写一元三次方求根函数,原理采用盛金求根法。形如#a*x**3 +b*x**2 + c*x +d = 0的式子,调用的时候shengjinSolution函数中a,b,c,d给定正确的值即可算出来。
代码片段和文件信息
import math
def caluCube(x):
if x > 0:
return math.pow(x float(1)/3)
elif x < 0:
return -math.pow(abs(x) float(1)/3)
else:
return 0
def getMiddenValue(a b c):
if a > b:
if b < c:
return b
elif a > c:
return c
else:
return a
else:
if a > c:
return a
elif b > c:
return c
else:
return b
#a*x**3 +b*x**2 + c*x +d = 0
def shengjinSolution(a b c d):
#print(“a=“ a “b=“ b “c=“ c “d=“ d)
A = b**2 - 3*a*c
B = b*c - 9*a*d
C = c**2 - 3*b*d
deltaJudge = B**2 - 4*A*C
x1 = x2 = x3 = 0
if A == B == 0:
print(“sheng 1“)
x1 = -b/3*a
x2 = -c/b
x3 = -3*d/c
elif deltaJudge > 0:
print(“sheng 2“)
Y1 = A*b + 3*a*(-B+math.sqrt(deltaJudge))/2
Y2 = A*b + 3*a*(-B-math.sqrt(deltaJudge))/2
cubeY1 = caluCube(Y1)
cubeY2 = caluCube(Y2)
x1 = (-b - (cubeY1+cubeY2))/(3*a)
x2 = complex((-b + 1/2*(cubeY1+cubeY2))/(3*a) math.sqrt(3)*(cubeY1-cubeY2)/(6*a))
x3 = complex((-b + 1/2*(cubeY1+cubeY2))/(3*a) -math.sqrt(3)
评论
共有 条评论