为什么MATLAB无法给出四次方程的正确结果?

时间:2015-09-23 08:15:51

标签: matlab equation-solving

虽然 MATLAB 拥有内置 solve()来解决四次方程,但solve()函数在某些情况下会提供一些错误信息。所以我编写了一个名为solveQuartic()的用户定义函数来解决四次方程的根。

我找到的引用是here

我的试用

function [res] = solveQuartic(a, b, c, d, e)
 p = (8*a*c - 3*b^2)/(8*a^2);
 q = (b^3 - 4*a*b*c + 8^a^2*d)/(8*a^3);

 delta0 = c^2-3*b*d + 12*a*e;
 delta1 = 2*c^3 - 9*b*c*d + 27*b^2*e + 27*a*d^2 - 72*a*c*e;

 Q = ((delta1 + sqrt(delta1^2 - 4*delta0^3))*0.5)^(1/3);
 S = 0.5*sqrt(-2/3*p + (Q + delta0/Q)/(3*a));

 x1 = -b/(4*a) - S - 0.5*sqrt(-4*S^2-2*p + q/S);
 x2 = -b/(4*a) - S + 0.5*sqrt(-4*S^2-2*p + q/S);
 x3 = -b/(4*a) + S - 0.5*sqrt(-4*S^2-2*p - q/S);
 x4 = -b/(4*a) + S + 0.5*sqrt(-4*S^2-2*p - q/S);

  res = [x1; x2; x3; x4];
end

TEST

res = solveQuartic(1,2,3,4,5)
-4.1425 - 0.0000i
 1.5669 + 0.0000i
 0.2878 + 3.3001i
 0.2878 - 3.3001i

但是,当我在 Mathematica 中实现公式时,如下所示:

solveQuartic[a_, b_, c_, d_, e_] :=
 Module[{p, q, delta0, delta1, Q, S, x1, x2, x3, x4},
  p = (8*a*c - 3*b^2)/(8*a^2);
  q = (b^3 - 4*a*b*c + 8^a^2*d)/(8*a^3);
  delta0 = c^2 - 3*b*d + 12*a*e; 
  delta1 = 2*c^3 - 9*b*c*d + 27*b^2*e + 27*a*d^2 - 72*a*c*e;
  Q = ((delta1 + Sqrt[delta1^2 - 4*delta0^3])*0.5)^(1/3); 
  S = 0.5*Sqrt[-2/3*p + (Q + delta0/Q)/(3*a)];

  x1 = -b/(4*a) - S - 0.5*Sqrt[-4*S^2 - 2*p + q/S]; 
  x2 = -b/(4*a) - S + 0.5*Sqrt[-4*S^2 - 2*p + q/S]; 
  x3 = -b/(4*a) + S - 0.5*Sqrt[-4*S^2 - 2*p - q/S]; 
  x4 = -b/(4*a) + S + 0.5*Sqrt[-4*S^2 - 2*p - q/S];
  {x1, x2, x3, x4}
]

solveQuartic[1, 2, 3, 4, 5] // MatrixForm

enter image description here

此外,我可以使用Solve[]来改变我的回答

Solve[{1, 2, 3, 4, 5}.Table[x^i, {i, 4, 0, -1}] == 0, x] // N // TableForm

enter image description here

问题

enter image description here

  • 有人知道原因吗? THX很多:)

1 个答案:

答案 0 :(得分:4)

您在p的计算中输入了一个拼写错误:您写的是8^a^2*d,而它应该是8*a^2*d

使用

q = (b^3 - 4*a*b*c + 8*a^2*d)/(8*a^3);

你得到了结果

res =

  -1.2878 - 0.8579i
  -1.2878 + 0.8579i
   0.2878 - 1.4161i
   0.2878 + 1.4161i

根据需要。