1 view (last 30 days)

x=sym('x');

endpoint_a = input('Plese input your endpoint a: ');

endpoint_b = input('Plese input your endpoint b: ');

tol = input('Plese input your tolerance: ');

n_0 = input('Plese input your maximum iterations : ');

F= input('Plese input your equation : ');

N=0;

a=subs(F,x,endpoint_a);

b=subs(F,x,endpoint_b);

% p= (subs(F,x,endpoint_a)+subs(F,x,endpoint_b))/2;

while(N <= n_0 && not(abs((endpoint_a-endpoint_b)/2) <= tol ))

N= N + 1;

p = (subs(F,x,endpoint_a)+subs(F,x,endpoint_b))/2;

p=b;

if (a*b) > 0

a=p;

else

endpoint_b=p;

end

end

John D'Errico
on 15 Sep 2019

I had to laugh, as I recognized your coding style from a previous question. Then I remembered your name. Note that

not(abs((endpoint_a-endpoint_b)/2) <= tol)

is the logical equivalent of the simpler

abs((endpoint_a-endpoint_b)/2) > tol

There is no need to make things more complicated than they need be.

Ok, given that, you are making a reasonable effort in these. Your problem in this one is an error of thought. You compute this:

p = (subs(F,x,endpoint_a)+subs(F,x,endpoint_b))/2;

The bisection method wants to evaluate the functino F at the midpoint of the current interval. So it needs to compare the values of F(a), f(b), and the value at the midpoint, thus F((a+b)/2).

What did you do? You computed the new point p as (F(a) + F(b))/2.

Next, you don't want to test if a*b is less than zero! In fact, here a and b are not even defined in your code. You do want to test if F(a)*F(b) is less than zero. That ensures that F(a) and F(b) have different signs.

So, you are going in a reasonable directino in this code. Not there yet. I think you can fix this, as your basic logic in the code is not bad. So try again, and show what you have if there is still a problem. I have confidence that you will get this right though on your own, with just a small nudge or two.

Opportunities for recent engineering grads.

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

Start Hunting!
## 0 Comments

Sign in to comment.