Displaying complex roots of quadratic equation

32 views (last 30 days)
This is my code.
a = input ('enter a: ');
b = input ('enter b: ');
c = input ('enter c: ');
xmin = input ('enter xmin: ');
xmax = input ('enter xmax: ');
step = (xmax - xmin)/100;
x = xmin : step : xmax;
y = a.*x.^2 + b.*x + c;
plot (x,y);
grid on;
xlabel ('x') ;
ylabel ('y');
xtickangle (45);
title (['Plot of f(x) = ', num2str(a), 'x.^2 + ', num2str(b), 'x + ', num2str(c)]);
D = b^2 - 4*a*c;
if D >= 0
x1 = (-b + sqrt (D)) / (2*a);
x2 = (-b - sqrt (D)) / (2*a);
fprintf ('Real zeros: %g, %g, \n', x1, x2)
fprintf ('Factored Form: f(x) = (x - %g)(x - %g) \n', x1, x2)
else
x1 = (-b + sqrt (D)) / (2*a);
x2 = (-b - sqrt (D)) / (2*a);
fprintf ('Complex Zeroes: %g, %g, \n', x1, x2)
fprintf ('Factored Form: f(x) = (x - (%g))(x - (%g)) \n', x1, x2)
end
When I have a quadratic with complex roots, the last line of the code only displays the real part of the root. Why? How can I change it so it displays both the real and imaginary part?

Answers (1)

Roger Stafford
Roger Stafford on 8 Mar 2018
On that 'else' part you need to find the two values real(x1) and imag(x1) as well as these two for x2. Then provide a display of all four quantities in each of your 'fprintf' lines. You might have something like this:
fprintf('Complex Zeros: %g + i*%g, %g + i*%g\n',real(x1),imag(x1),real(x2),imag(x2))

Categories

Find more on Visual Exploration in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!