- 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.
Writing code for bisection method; then storing values for each iteration of the loop.
5 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Bradley Johnson
am 30 Mär. 2020
Kommentiert: Geoff Hayes
am 30 Mär. 2020
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 Kommentare
Akzeptierte Antwort
Geoff Hayes
am 30 Mär. 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:
2 Kommentare
Geoff Hayes
am 30 Mär. 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
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Logical finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!