Writing code for bisection method; then storing values for each iteration of the loop.

3 次查看(过去 30 天)
Hello, I am trying to write a code for bisection method for a class project. I cant figure out why my code wont finish running and give me the root. I also need to store the values of a, b, c, x, and y for each iteration to plot them and make a table with? Can anybody help? Thank you.
clear; clc;
f=@(x)2 * x^4 +3 * x^3 - 11 * x^2 - 9 * x + 15 ;
a=input('\n Enter left point of interval ');
b=input('\n Enter right point of interval ');
toll= 1e-10;
err=abs(b-a);
c = ( a + b )/2;
if f(a) *f(b) > 0
disp 'Enter valid interval!!!');
else
c = ( a + b) /2;
toll= 1e-2;
err=abs(b-a);
while err > toll
if f(c) == 0
fprintf( 'The Root is: %4.4f\n', c)
else
c = ( a + b )/2;
x = abs( b - c);
y = abs(f(c));
if ( f(a) * f(c)) <= 0
c = b;
else
if ( f(b) * f(c)) <= 0
a = c;
end
end
end
end
end

采纳的回答

Geoff Hayes
Geoff Hayes 2020-3-30
Bradley - look closely at the condition for the while loop
while err > toll
. Since toll (the tolerance) is fixed, how or where does err get set? You initialize it on the previous line but never reset this variable using the new a and b. A couple of other things:
  • try and avoid using something like f(c) == 0 when comparing floats/doubles. Try a tolerance check instead similar to abs(f(c)) < eps.
  • only iterate for a maximum number of iterations so that you don't get stuck in the while loop: so either iterate until the error is less than the tolerance OR unti the max number of iterations has been reached.
  • use arrays to store values that you may want to plot outside of the loops.
  2 个评论
Bradley Johnson
Bradley Johnson 2020-3-30
I got the program to work, thank you for your help.
How would i go about using arrays to stroe the values?
Geoff Hayes
Geoff Hayes 2020-3-30
Suppose that you allow for 100 maximum iterations for your loop. Then for x and y you could do
maxIterations = 100;
atIter = 0;
x = zeros(maxIterations,1);
y = zeros(maxIterations,1);
while err > toll && atIter <= maxIterations
atIter = atIter + 1;
if f(c) == 0
fprintf( 'The Root is: %4.4f\n', c)
else
c = ( a + b )/2;
x(atIter) = abs(b - c);
y(atIter) = abs(f(c));
if ( f(a) * f(c)) <= 0
c = b;
elseif ( f(b) * f(c)) <= 0 % combined the else and if into an elseif
a = c;
end
end
end

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by