MATLAB Answers

0

Displaying complex roots of quadratic equation

Asked by Valentina Sandberg on 7 Mar 2018
Latest activity Answered by Roger Stafford on 8 Mar 2018
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?

  0 Comments

Sign in to comment.

Tags

1 Answer

Roger Stafford 님의 답변 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))

  0 Comments

Sign in to comment.