Consider the cubic equation ax3 + bx2 + cx + d = 0, (1) where a, b, c, and d are
ID: 3785828 • Letter: C
Question
Consider the cubic equation ax3 + bx2 + cx + d = 0, (1) where a, b, c, and d are real input coefficients. Develop a matlab program
to find all roots of equation (1) using the methods discussed in class. Your program can not use the matlab built-in functions fzero and roots.
Your program will be stress-tested against cubic equations that may have 1. (40 points) random roots; or 2. (20 points) very large or very small roots; or 3. (20 points) multiple roots or nearly multiple roots; or 4. (20 points) less than 3 roots or more than 3 roots
Explanation / Answer
function [root,total] = mycubic(a,b,c)
Q=(a*a-3*b)/9;
R=(2*a*a*a-9*a*b+27*c)/54;
% Three real roots
if(R*R<Q*Q*Q)
theta=cos(R/sqrt(Q*Q*Q));
root(1)=-2.0*sqrt(Q)*cos((theta/3) )-a/3;
root(2)=-2.0*sqrt(Q)*cos((theta+2*pi)/3)-a/3;
root(3)=-2.0*sqrt(Q)*cos((theta-2*pi)/3)-a/3;
total = 3;
% One real root and two complex conjugates
else
A = pow(fabs(R)+sqrt(R*R-Q*Q*Q),1.0/3.0);
if(R>0.0) A =- A;
if(A!=0.0) B=Q/A;
else B=0.0;
end
root(1) = (A+B) - a/3;
if(A!=B)
total = 1;
end
%Imaginary part of roots is zero giving one more real root
root(1) = -(A+B)/2 - a/3;
total = 2;
end