Displaying complex roots of quadratic equation

6 Ansichten (letzte 30 Tage)
Valentina Sandberg
Valentina Sandberg am 7 Mär. 2018
Beantwortet: Roger Stafford am 8 Mär. 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?

Antworten (1)

Roger Stafford
Roger Stafford am 8 Mär. 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))

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by