# Coding a quadratic root finder

조회 수: 5(최근 30일)
Will Murphy 2020년 2월 17일
편집: James Tursa 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 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.
##### 댓글 수: 0표시숨기기 이전 댓글 수: -1

댓글을 달려면 로그인하십시오.

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

댓글을 달려면 로그인하십시오.

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
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.

댓글을 달려면 로그인하십시오.

### Community Treasure Hunt

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

Start Hunting!