ast*_*rog 9 python algorithm math cubic
作为我正在编写的程序的一部分,我需要准确地求解一个三次方程式(而不是使用数字根查找器):
a*x**3 + b*x**2 + c*x + d = 0.
Run Code Online (Sandbox Code Playgroud)
我正试图从这里使用方程式.但是,请考虑以下代码(这是Python,但它是非常通用的代码):
a = 1.0
b = 0.0
c = 0.2 - 1.0
d = -0.7 * 0.2
q = (3*a*c - b**2) / (9 * a**2)
r = (9*a*b*c - 27*a**2*d - 2*b**3) / (54*a**3)
print "q = ",q
print "r = ",r
delta = q**3 + r**2
print "delta = ",delta
# here delta is less than zero so we use the second set of equations from the article:
rho = (-q**3)**0.5
# For x1 the imaginary part is unimportant since it cancels out
s_real = rho**(1./3.)
t_real = rho**(1./3.)
print "s [real] = ",s_real
print "t [real] = ",t_real
x1 = s_real + t_real - b / (3. * a)
print "x1 = ", x1
print "should be zero: ",a*x1**3+b*x1**2+c*x1+d
Run Code Online (Sandbox Code Playgroud)
但输出是:
q = -0.266666666667
r = 0.07
delta = -0.014062962963
s [real] = 0.516397779494
t [real] = 0.516397779494
x1 = 1.03279555899
should be zero: 0.135412149064
Run Code Online (Sandbox Code Playgroud)
因此输出不为零,因此x1实际上不是解决方案.维基百科文章中有错误吗?
ps:我知道numpy.roots会解决这种方程,但我需要为数百万个方程做到这一点,所以我需要实现它来处理系数数组.
A. *_*Rex 24
维基百科的符号(rho^(1/3), theta/3)并不意味着它rho^(1/3)是真实的部分,theta/3而是虚构的部分.相反,这是在极坐标中.因此,如果你想要真正的部分,你会采取rho^(1/3) * cos(theta/3).
我对您的代码进行了这些更改,它对我有用:
theta = arccos(r/rho)
s_real = rho**(1./3.) * cos( theta/3)
t_real = rho**(1./3.) * cos(-theta/3)
Run Code Online (Sandbox Code Playgroud)
(当然,s_real = t_real这里因为cos是偶数.)