Borrar filtros
Borrar filtros

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

4 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Geoff Hayes
Geoff Hayes el 30 de Mzo. de 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 comentarios
Bradley Johnson
Bradley Johnson el 30 de Mzo. de 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 el 30 de Mzo. de 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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Logical en Help Center y File Exchange.

Productos


Versión

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by