Coding a quadratic root finder

2 次查看(过去 30 天)
Will Murphy
Will Murphy 2020-2-17
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.

回答(3 个)

Bhaskar R
Bhaskar R 2020-2-17
You no need to do program to find roots of the quadratic quation, MATLAB has built in command roots
a=input('a=')
b=input('b=')
c=input('c=')
r = roots([a,b,c]) %% coeffients
to get real and and imaginary parts from the roots you can apply real and imag after that you can perform conditioning to state which kind they are.

Sindar
Sindar 2020-2-17
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 个评论
Sindar
Sindar 2020-2-17
assuming this is a code exercise; if you just want the functionality, use Bhaskar's root solution

请先登录,再进行评论。


James Tursa
James Tursa 2020-2-17
编辑:James Tursa 2020-2-17
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.

类别

Help CenterFile Exchange 中查找有关 Mathematics and Optimization 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by