Asked by Erik Ramirez
on 15 Sep 2019 at 20:38

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

Answer by John D'Errico
on 15 Sep 2019 at 21:52

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.

Erik Ramirez
on 16 Sep 2019 at 0:07

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 : ');

g=(endpoint_a + endpoint_b)/2;

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;

%p = subs(F,x,g);

p = subs(F,x,g);

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

N= N + 1;

p = subs(F,x,g);

g=p;

if a*b < 0

a=p;

else

b=p;

end

end

p

i changed the (f(a)+f(b))/2 to f((a+b)/2)

and i did f(a)*f(b) is less than zero.[a=subs(F,x,endpoint_a] and [b=subs(F,x,endpoint_b)]

now im getting an error in this loop. I cant figure out the issue. For the "if" loop is it not a=p and b=p?

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.