The roots of a quadratic equation ax^2 + bx + c = 0 are given by the formula: x
ID: 3818071 • Letter: T
Question
The roots of a quadratic equation ax^2 + bx + c = 0 are given by the formula: x = - b plusminus Squareroot b^2 - 4 ac/2a Write a function that takes as input the coefficients a, b, c and returns as output the roots x_1, x_2 of the quadratic equation. Let x_1 be the smaller of the two roots. If a is zero, print a warning message informing the user of the situation. Then, solve the linear equation for the single root x_1 = -c/b and set x_2 = NaN. If b^7 - 4 ac is negative, print a warning message informing the user of the situation Then, solve the equation anyways to find and return the complex roots If b^2 - 4ac is zero, set x_2 = x_1 = -b/2a If any of a. b, c are not scalar numbers, print an error message informing the user of the situation and set x_1 = x_2 = NaN Test your function extensively with an adversarial mindset Try to break it (make it crash or behave in undefined or erratic ways). Every time you break it, fix it. Your goal is to make the function able to handle any possible input, and to fail gracefully when the inputs are invalid Useful functions for this include isnumeric, isscalar, isreal, isinf, isnan.Explanation / Answer
function [x1 x2] = rootsOfQuadratic(a, b, c)
if ~isscalar(a) || ~isscalar(b) || ~isscalar(c)
x1 = NaN;
x2 = NaN;
return;
end
if a == 0
fprintf('The equation is not quadratic. ');
x1 = -c / b;
x2 = NaN;
return;
det = b^2 - 4*a*c;
if det < 0
fprintf('The roots are imaginary. ');
x1 = (-b - sqrt(det)) / (2 * a);
x2 = (-b + sqrt(det)) / (2 * a);
return;
end
if det == 0
x2 = -b / (2 * a);
x1 = x2;
return;
end
x1 = (-b - sqrt(det)) / (2 * a);
x2 = (-b + sqrt(det)) / (2 * a);
end
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.