MATLAB Answers

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

11 views (last 30 days)
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

  0 Comments

Sign in to comment.

Accepted Answer

Geoff Hayes
Geoff Hayes on 30 Mar 2020
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 Comments

Bradley Johnson
Bradley Johnson on 30 Mar 2020
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 on 30 Mar 2020
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

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Products


Release

R2019a