Coding a quadratic root finder
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Hi I'm trying to code a quadratic root finder that works in the cases that b^2 - 4ac is positive, negative and zero as well as non-existent in the case a=b=0 & c isnt, with a given a,b & c such ax^2+bx+c=0
So far, I have:
a=input('a=')
b=input('b=')
c=input('c=')
d=sqrt(b*b-4*a*c)
if d>0
fprintf('two real roots exist:\n');
x1=(d-b)/(2*a)
x2=(-d-b)/(2*a)
elseif d==0
fprintf('one real roots exist:\n');
x=-b/(2*a)
elseif d<0
fprintf('two complex roots exist:\n')
I dont know what to do to compute these roots into the form a+bi and a-bi
Furthermore I dont know how to compute a=b=0 and c is nonzero.
How do I finish off this code, any help would be greatly appreciated as I only started coding the other day. Furthermore if I am wrong elswhere please let me know where so I know how to do this in the future.
0 Kommentare
Antworten (3)
Sindar
am 17 Feb. 2020
One error: you want to check the sign of (b*b-4*a*c), not sqrt(b*b-4*a*c)
The case of two complex roots works exactly like two real roots. Since (b*b-4*a*c) is negative, the sqrt will be complex and thus so will your x's. If you want to write x=A+Bi:
A=real(x);
B=imag(x);
For cases where there are no roots ( a=b=0 & c , second root of d=0), fill them with NaN in case you use them later:
elseif d==0
if %check a=b=0 & c isn't
fprintf('no roots exist:\n');
x1=NaN;
x2=NaN;
else
fprintf('one real roots exist:\n');
x1=-b/(2*a);
x2=NaN;
end
1 Kommentar
Sindar
am 17 Feb. 2020
assuming this is a code exercise; if you just want the functionality, use Bhaskar's root solution
James Tursa
am 17 Feb. 2020
Bearbeitet: James Tursa
am 17 Feb. 2020
I would advise having your logic figure out what situation you have before you start solving things. E.g., something like
if( a == 0 ) % Not Quadratic
if( b == 0 ) % Constant case
if( c == 0 ) % OK
else % not OK
end
else % Linear case
end
else % Quadratic
d2 = b^2 - 4*a*c;
if( d2 == 0 )
elseif( d2 > 0 )
else
end
end
Hint: The MATLAB sqrt( ) function will automatically produce a complex result if the input argument is negative. You don't have to write special code to figure out how to get that result.
0 Kommentare
Siehe auch
Kategorien
Mehr zu Mathematics and Optimization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!