Finding and Identifying Roots
7 次查看(过去 30 天)
显示 更早的评论
I am attempting to write a code that classifies cubic function as simpler, monotone, or neither. To do this I must calculate the derivative of the cubic function and find its roots. So far the code I have is as follows:
%Solicit Data Needed and Display Data
a = input ('Enter a: ');
b = input ('Enter b: ');
c = input ('Enter c: ');
d = input ('Enter d: ');
fprintf ('Cubic Equation: f(x) = ax^3 + bx^2 + cx + d, a = %10.6f, b = %10.6f, c = %10.6f, d = %10.6f\n', a,b,c,d);
%Give error if a = 0
if a == 0
error ('Please enter a non-zero value for a!')
end
%Print the Derivative of the cubic function
fprintf ('df/dx = 3ax^2 +2bx +c\n');
%Obtain the Roots of the Derivative
r1 = ((-2*b) + sqrt (((2*b)^2 - (4*3*a*c))/(6*a)));
r2 = ((-2*b) - sqrt (((2*b)^2 - (4*3*a*c))/(6*a)));
fprintf ('The first root of the derivative of f is %10.6f\n' , r1);
fprintf ('The second root of the derivative of f is %10.6f\n' , r2);
The equation for the roots should be correct as I have checked it on my calculator and have double checked all the parenthesis, but for some reason when the program is ran the command window displays the wrong values. I don't know why this is occurring. I also need to identify whether the roots are complex and I cant seem to figure out how to do so. Thanks in advance.
Note: I am at a beginner level and have just recently started learning MATLAB...I may be missing something very obvious.
0 个评论
采纳的回答
Star Strider
2018-10-15
The parentheses are not correctly placed.
The entire quantity ‘(-2*b) + sqrt((2*b)^2 - (4*3*a*c)))’ should be divided by ‘(6*a)’:
r1 = ((-2*b) + sqrt((2*b)^2 - (4*3*a*c)))/(6*a);
Correct ‘r2’ similarly.
2 个评论
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!