Python 解四次方程代码示例
import math
def solve_quartic(a, b, c, d, e):
'''
解四次方程
参数:
a, b, c, d, e:四次方程的系数
返回值:
四个解的列表,如果有重复的解则只返回一次
如果无实数解,则返回空列表
'''
# 如果 a=0,则为三次或次以下方程,直接解出即可
if a == 0:
return solve_cubic(b, c, d, e)
# 将四次方程转化为标准形式:x^4 + ax^3 + bx^2 + cx + d = 0
# 通过将 x = y - a/4 转化,可消去 x^3 的系数
p = (8*a*c - 3*b**2) / (8*a**2)
q = (b**3 - 4*a*b*c + 8*a**2*d) / (8*a**3)
delta = (c**2 - 3*b*d + 12*a*e) / (8*a**2)
# 如果 delta 大于零,则有两个实数解,直接求解即可
if delta > 0:
t1 = math.sqrt(delta)
t2 = math.sqrt(2*p)
# 四个解
x1 = (-b - t1 - t2) / (4*a)
x2 = (-b - t1 + t2) / (4*a)
x3 = (-b + t1 - t2) / (4*a)
x4 = (-b + t1 + t2) / (4*a)
return [x1, x2, x3, x4]
# 如果 delta 等于零,则有两个实数解,一个重复两次
elif delta == 0:
t1 = math.sqrt(2*p)
# 三个解
x1 = (-b - 2*t1) / (4*a)
x2 = (-b + t1) / (4*a)
x3 = (-b + t1) / (4*a)
return [x1, x2, x3]
# 如果 delta 小于零,则有两个共轭复数解
else:
t1 = math.acos(3*q / (2*p) * math.sqrt(2/p))
t2 = -t1
# 两个实数解
x1 = (-b - 2*math.sqrt(p)*math.cos(t1/3)) / (4*a)
x2 = (-b - 2*math.sqrt(p)*math.cos(t2/3)) / (4*a)
# 两个共轭复数解
x3 = (-b + math.sqrt(p)*(math.cos(t1/3) + math.sqrt(3)*math.sin(t1/3)*1j)) / (4*a)
x4 = (-b + math.sqrt(p)*(math.cos(t2/3) + math.sqrt(3)*math.sin(t2/3)*1j)) / (4*a)
return [x1, x2, x3, x4]
原文地址: https://www.cveoy.top/t/topic/m55H 著作权归作者所有。请勿转载和采集!