Complex Roots of a quadratic function
5 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hello,
I have this code that take inputs from a user to solve for the roots of a quadratic equation. I am focused on getting the complex roots of this and am having trouble getting anything to display. I am using a function where it takes 3 inputs of a,b,c and the code should process it to output the roots of x1 and x2. Right now, I am not getting anything to display after doing the inputs. I am very confused and any help would be much appreciated.
function [x1,x2] = Quadratic(a,b,c)
%ax^2+ bx+ c = 0
if b^2 < 4*a*c
x1 = (-b +sqrt(b^2 - 4*a*c))/(2*a);
x2 = (-b -sqrt(b^2 - 4*a*c))/(2*a);
disp(' x1 and x2 are complex roots')
disp(' x1',x1)
disp(' x2',x2)
elseif b^2 == 4*a*c
x1 = -b/(2*a);
x2=x1;
disp('equal roots')
disp(' x1',x1)
disp(' x2',x2)
else
x1 = (-b + sqrt(b^2 - 4*a*c))/(2*a);
x2 = (-b - sqrt(b^2 - 4*a*c))/(2*a);
disp(' x1',x1)
disp(' x2',x2)
end
end
0 commentaires
Réponses (2)
Dyuman Joshi
le 16 Sep 2023
Modifié(e) : Dyuman Joshi
le 16 Sep 2023
"Right now, I am not getting anything to display after doing the inputs."
It is because you have not called the function. To get output(s) from a function, you have call the function with input(s) (if there are any required).
Additionally, when a quantity is used multiple times in a code, it is better to store it in a variable rather than evaluating the quantity repeatedly. In your case, it would be the discriminant and the roots.
%Random values for example, as input is not supported in live editor
a = 3; %input('Enter value for a: ')
b = 5; %input('Enter value for b: ')
c = 9; %input('Enter value for c: ')
%Calling the function
[x1,x2] = Quadratic(a,b,c);
%Alternatively you can directly call a function, like this
[X1,X2] = Quadratic(1,2,1);
%Calling a function directly
[x_1,x_2] = Quadratic(2,6,4);
function [x1,x2] = Quadratic(a,b,c)
%ax^2+ bx+ c = 0
%Computing and storing the discriminant as a variable
%to use for comparison multiple times
D = b^2 - 4*a*c;
%Doing the same for roots
x1 = (-b + sqrt(D))/(2*a);
x2 = (-b - sqrt(D))/(2*a);
if D<0
disp('x1 and x2 are complex roots')
elseif D==0
disp('equal roots')
else
%Added statement
disp('real and unequal roots')
end
disp('x1 = ')
disp(x1)
disp('x2 = ')
disp(x2)
end
23 commentaires
Dyuman Joshi
le 17 Sep 2023
Modifié(e) : Dyuman Joshi
le 19 Sep 2023
Looking at the screenshot you have attached - remove any (non-empty) lines before
function [x1,x2] = Quadratic(a,b,c)
And your code should work properly.
@Ant, if my answer helped solve your problem, please consider accepting it.
Voir également
Catégories
En savoir plus sur Symbolic Math Toolbox dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!