Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the cubic equation ax3 + bx2 + cx + d = 0, (1) where a, b, c, and d are

ID: 1944116 • 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 appropriate methods. Your program can not use the matlab built-in
functions fzero and roots.
You should turn in a .m file cubicxxx.m which contains a matlab function of the form
function [rts,info] = cubicxxx(a,b,c,d)
where xxx is your student id, rts is the vector of roots and info is your output message.
Your program will be stress-tested against cubic equations that may have
1. random roots; or
2. very large or very small roots; or
3. multiple roots or nearly multiple roots; or
4. less than 3 roots or more than 3 roots.
You will receive credit for a test polynomial only if your program gets the number of roots
correctly, and only then will each correct root (accurate to within a relative error of at most 10^-10,
as compared to the roots function in matlab) receive additional credit.
Your program will receive 0 points if the strings fzero or roots (both in lower case letters)
show up anywhere in your .m file.

Explanation / Answer

The following code will give you a test harness that tests random polynomials (i.e. random roots) with both your code and roots.

clear variables; clc; close all;

nTests = 100;
nPass = 0;
nAccurate = 0;
tolerance = 1e-10;

for i = 1:nTests
p = rand(4,1); % or a function that generates a test polynomial
referenceRoots = roots(p);

[myRoots, info] = cubicxxx(p(1), p(2), p(3), p(4));

try
assert(numel(unique(myRoots))==numel(unique(referenceRoots)),'Not the correct number');
nPass = nPass + 1;
assert(all(abs(sort(myRoots)./sort(referenceRoots)-1)<tolerance),'Not accurate enough');
nAccurate = nAccurate + 1;
catch error
fprintf(2,'%s ',error.message);
fprintf('Polynomial: %g a*x^3 + %gb* x^2 + %gc* x + %gd ', p(1), p(2), p(3), p(4));
disp(info);

disp('Reference, Mine');
disp([referenceRoots, myRoots]);
end


%check this out....
end
fprintf(' ');
fprintf('Score: %d / %d for number of roots ',nPass , nTests);
fprintf('Score: %d / %d for accuracy ',nAccurate, nTests);