MATLAB problem: A) Write a MATLAB function that computes the roots of f(x) = ax
ID: 3664723 • Letter: M
Question
MATLAB problem:
A) Write a MATLAB function that computes the roots of f(x) = ax2 + bx + c, where a, b, and c are real constants.
Write the function call as [x1,x2] = quadroots(a,b,c) where x1 and x2 are the two roots. Make sure to minimize
the effect of loss of significance, and use as few arithmetic operations as possible.
B) Write the script file that computes your function for both f(x) = x2 - 105 x + 1 and f(x) = x2 + 105 x + 1, and test
it by computing both f(x1) and f(x2) for both functions.
Explanation / Answer
A.
MATLAB function that computes the roots of f(x) = ax2 + bx + c, where a, b, and c are real constants
PROGRAM:
function [r1r,r1i,r2r,r2i] = quadric ( a,b,c,opt );
% -------------------- implementation ----------------------
small = 0.00000001;
r1r = 0.0;
r1i = 0.0;
r2r = 0.0;
r2i = 0.0;
discrim = b*b - 4.0 *a*c;
%a
%b
%c
%discrim
% --------------------- real roots --------------------------
if ( abs(discrim) < small )
r1r = -b / ( 2.0 *a );
r2r = r1r;
% if (opt=='U')
% r2r = 99999.9;
% end;
else
if abs(a) < small
r1r = -c/b;
else
if ( discrim > 0.0 )
r1r = ( -b + sqrt(discrim) ) / ( 2.0 *a );
r2r = ( -b - sqrt(discrim) ) / ( 2.0 *a );
else
% ------------------ complex roots --------------------
if (opt=='I')
r1r = -b / ( 2.0 *a );
r2r = r1r;
r1i = sqrt(-discrim) / ( 2.0 *a );
r2i = -sqrt(-discrim) / ( 2.0 *a );
else
r1r = 99999.9;
r2r = 99999.9;
end;
end;
end;
end;
b.
function r = quadroot(p)
% Check array class.
if ~isnumeric(p)
error('P must be a numeric array.');
end
% Check array size.
if (ndims(p) ~= 2) | (size(p, 1) ~= 1)
error('P must be row vector.');
end
a = p(1);
b = p(2);
c = p(3);
if a == 0
if b == 0
if c == 0
%
% a, b, c are zero: 0 = 0
%
error('All coefficients are zero');
else
%
% a, b are zero: c = 0;
%
error('Constant equation');
end
else
if c == 0
%
% a, c are zero: b*x = 0
%
r = 0;
return;
else
%
% a is zero: b*x + c = 0
%
r = -c/b;
return;
end
end
else
if b == 0
if c == 0
%
% b, c are zero: a*x^2 = 0
%
r = [0 0];
return;
else
%
% b is zero: a*x^2 + c = 0
%
t = sqrt(c/a);
r = [t -t];
return;
end
else
if c == 0
%
% c is zero: a*x^2 + b*x = 0;
%
r = [0 -b/a];
return;
else
%
% none of a, b, c are zero: a*x^2 + b*x + c = 0
%
d = b*b - 4*a*c; % discriminant
if d == 0
% two identical roots
t = -b/(2*a);
r = [t t];
return;
else
if sign(real(sqrt(d))) == sign(real(b))
t = -b - sqrt(d);
else
t = -b + sqrt(d);
end
r = [ t/(2*a) (2*c)/t ];
return;
end
end
end
end
% we should never get here
error('Internal error');
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.