How can i run my bisection code in matlab what are error in my code?

164 Views Asked by At

Your code bisection.m

function p = bisection3(~,~,~)
f=input('enter equation in form of string:');
a=input('enter start limit valur of a');
b=input('enter start limit valur of b');
f=inLine(f);

if f(a)*f(b)>0 
disp('Wrong choice bro')
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

Error

 enter equation in form of string:x^3+2*x^2+x+4
 Error using input
 Undefined function or variable 'x'.

 Error in bisection3 (line 2)
 f=input('enter equation in form of string:');
1

There are 1 best solutions below

4
On

I see different problems:

  • a) The main one is that your program can only work if $f(a)<0$, because you have to preserve the fact that, at any moment, $f(a) \times f(b)\leq 0.$ Thus, what you have to do just after the computation of $f(m)$ is to test whether $f(a) \times f(m) \leq 0$; if yes set (new)b=m else set (new)a=m.

  • b) A little less important is the fact that your test "$F(m)==0$" is useless, because this event is likely never to occur. You should remove it.

  • c) (in connection with remark b) replace the "while" loop by a "for" loop, for example by "for k=1:10... end". Why 10 ? Because the error at the beginning is measured by $b-a$. After 10 loops, the error has become $\dfrac{b-a}{2^{10}}$ i.e., has approximately been divided by one thousand ! You are one thousand times more precise...

  • d) A good reference on the mathworks site (https://fr.mathworks.com/matlabcentral/fileexchange/33748-bisection-method/content/bisection.m)