Borrar filtros
Borrar filtros

Coding a quadratic root finder

2 visualizaciones (últimos 30 días)
Will Murphy
Will Murphy el 17 de Feb. de 2020
Editada: James Tursa el 17 de Feb. de 2020
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.

Respuestas (3)

Bhaskar R
Bhaskar R el 17 de Feb. de 2020
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 el 17 de Feb. de 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 comentario
Sindar
Sindar el 17 de Feb. de 2020
assuming this is a code exercise; if you just want the functionality, use Bhaskar's root solution

Iniciar sesión para comentar.


James Tursa
James Tursa el 17 de Feb. de 2020
Editada: James Tursa el 17 de Feb. de 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.

Categorías

Más información sobre Mathematics and Optimization en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by