How to keep my complex root answers un-simplified?

I've created a formula to calculate complex roots in editor and have the following:
a=input('Enter the value for a: ');
b=input('Enter the value for b: ');
c=input('Enter the value for c: ');
if b^2 > 4*a*c
root_1=(-b+sqrt(b^2-4*a*c))/2*a;
root_2=(-b-sqrt(b^2-4*a*c))/2*a;
fprintf('\n')
disp('Roots are real and distinct:')
fprintf(1,'Root1= %0.0f \n',root_1);
fprintf(1,'Root2= %0.0f \n',root_2);
elseif b^2 == 4*a*c
root_1=-b/(2*a);
root_2=-b/(2*a);
fprintf('\n')
disp('Roots are repeated:')
fprintf(1,'Root1=Root2= %0.0f \n',root_1);
elseif b^2 < 4*a*c
root_1=(-b/2*a)+(sqrt(4*a*c-b^2)/2*a);
root_2=(-b/2*a)-(sqrt(4*a*c-b^2)/2*a);
fprintf('\n')
disp('Roots are complex:')
fprintf(1,'Root1= %0.0f \n',root_1);
fprintf(1,'Root2= %0.0f \n',root_2);
end
So far everything works fine but I don't want the last "elseif" command to simplify the imaginary equation.
For instance if my (a,b,c) are (1,8,25), respectfully, the answer that I would like to have is:
Root1= -4+3i
Root2= -4-3i
How do I keep it this way or at least have the "i"?

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 28 Jun. 2012

0 Stimmen

fprintf(1,'Root1= %0.0f%+0.0fi\n', real(root_1), imag(root_1));

9 Kommentare

Aaron
Aaron am 28 Jun. 2012
Tried this command and got this answer:
Roots are complex: Root1= -1+0i Root1= -7+0i
Tom
Tom am 28 Jun. 2012
Look very carefully at your equations for root_1 and root_2 for the complex case...
Aaron
Aaron am 28 Jun. 2012
I've tried but can't seem to find where I'm messing up?!
Good eyes, Tom.
Tom
Tom am 28 Jun. 2012
Bearbeitet: Tom am 28 Jun. 2012
It's one of those things:
sqrt(4*a*c-b^2)
Also, for the first pair of equations, you need brackets for the 2*a part:
(-b+sqrt(b^2-4*a*c))/(2*a)
Aaron
Aaron am 28 Jun. 2012
Bearbeitet: Aaron am 28 Jun. 2012
How could that be? The sqrt worked find with my other equations.
You did not use the same sqrt with your other equations.
Tom
Tom am 28 Jun. 2012
It might be worth checking it with a known solution (e.g. http://www.mathgoodies.com/calculators/quadratic_equations.html)- try for example a=3,b=4,c=1
Aaron
Aaron am 28 Jun. 2012
Bearbeitet: Aaron am 28 Jun. 2012
Sonovagun!! I should have caught that. Thank you.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Community Treasure Hunt

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

Start Hunting!

Translated by