Adding Plotting to bisection method

Not sure what the c is in this bisection method. Also I would like to add plotting of the intervals
function [x,e] = MyBisectFunc(f, a1,b1, number)
format long
c1 = f(a1); d1 = f(b1);
if c1*d1 > 0.0
error ('Func has same sign at both endpoints')
end
for i = 1:number
x = (a1 + b1) /2;
y = f(x);
disp([x,y])
if y == 0.0
e = 0
break
end
if c*y < 0
b = x
else
a = x
end
end
x = (a1 + b1)/2;
e = (b1 - a1) /2;

Réponses (1)

Alan Stevens
Alan Stevens le 13 Fév 2021
Like so:
f = @(x) x^2 - 2; % arbitrary function
a1 = 0; b1 = 1.8; % initial end-points
c1 = f(a1); d1 = f(b1);
if c1*d1 > 0.0
error ('Func has same sign at both endpoints')
end
number = 20;
for i = 1:number
c1 = f(a1); d1 = f(b1);
if c1*d1 > 0.0
error ('Func has same sign at both endpoints')
end
x = (a1 + b1) /2;
y = f(x);
disp([x,y])
if abs(y) < 10^-8
break
end
if c1*y < 0 % c1 not c
b1 = x;
else
a1 = x;
end
end

6 commentaires

gracias claude
gracias claude le 13 Fév 2021
What's this ?
`if abs(y) < 10^-8
break
end`
gracias claude
gracias claude le 13 Fév 2021
How do I plot the intervals ?
Alan Stevens
Alan Stevens le 13 Fév 2021
Never test for exact equality when dealing with floating point numbers, test for a small difference from the desired value.
For the intervals you could keep a record of the a1 and b1 values (by a1(i) = ...etc) then plot them against 1:number at the end.
gracias claude
gracias claude le 13 Fév 2021
so like
if ...
invervalX(i) = x;
end
else
intervalY(i) = x;
for i = 1:number
plot(intervalX(i), intervalY(i))
end;
gracias claude
gracias claude le 13 Fév 2021
not very familar with the syntax
This section
if abs(y) < 10^-8
break
end
breaks out of the loop if the condition is met. Probably best to remove it if you want to plot the intervals. You'll need to do something like:
f = @(x) x^2 - 2; % arbitrary function
number = 20; % number of iterations
lo = zeros(1,number); % initialise vector
hi = zeros(1,number);
lo(1) = 0;
hi(1) = 1.8;
for i = 1:number-1
flo = f(lo(i)); fhi = f(hi(i));
if flo*fhi > 0.0
error ('Func has same sign at both endpoints')
end
mid = (lo(i) + hi(i)) /2;
fmid = f(mid);
if flo*fmid < 0 % c1 not c
hi(i+1) = mid;
lo(i+1) = lo(i);
else
lo(i+1) = mid;
hi(i+1) = hi(i);
end
end
disp([mid fmid])
plot(1:number,abs(hi-lo),'o'),grid
xlabel('iteration number'), ylabel('interval')

Connectez-vous pour commenter.

Catégories

En savoir plus sur Graphics Objects dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by