Trying to do bisection, new to MATLAB
5 views (last 30 days)
Show older comments
My code is:
function f = bisection2(g,a,b)
g= @x 3*x - e^x
while 1
p =(a+b)/2;
if p-a< 10^-5, break;end
if g(a)*g(p)>0
a = p;
else
b = p;
end
end %while 1
I have tried defining g in a separate .m file, but I keep getting an error in that line. 3x-e^x is the function I am trying to apply bisection to. I am using R2018b.
0 Comments
Answers (1)
ANKUR KUMAR
on 5 Oct 2018
As your equation negative value at both ends. So bisection can not be possible for your equation. I am giving this example by taking different function.
g= @(x) 2*x + sin(x)
bisection(g,-5,10)
function p = bisection(f,a,b)
f(a)
f(b)
if f(a)*f(b)>0
disp('The function has positive value at the end points of interval.');
disp('The root can''t be found using bisection method, use some other method.');
else
p = (a + b)/2;
err = abs(f(p));
while err > 1e-7
if f(a)*f(p)<0
b = p;
else
a = p;
end
p = (a + b)/2;
err = abs(f(p));
end
end
end
References:
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!