Asked by Erik Ramirez
on 5 Sep 2019

x= sym('x');

p = 0.6;

F = x^5+4*x^2-1;

F_prime = diff(F);

N=0;

q = p - subs(F,x,p)/subs(F_prime,x,p);

while(N < 100 && not(abs(p-q) <= .00001 ))

N=N+1;

p = q;

q = p - ((subs(F,x,p))./(subs(F_prime,x,p)));

end

if(N == 100)

print("Too many iterations");

else

display(q)

end

Answer by John D'Errico
on 5 Sep 2019

Accepted Answer

When you have a problem like this, plot the function. In fact, plot the function anyway!

Next, it is a bad idea to use variables like p and q, then swaping them back and forth. Use variable names that make sense!!!!!

Next, don't keep things symbolic. That causes problems, because you don't know how to work with symbolic variables that well. Use functions instead.

I'll start with a symbolic function, then differentiate it in symbolic form. But then alllow matlabFunction to convert it to a function handle.

Finally, I cleaned up the logic in your code.

x = sym('x');

xcurrent = 0.5; % start point

xold = inf; % the first time through, you need to pass the while condition

F = x^3+4*x^2-10;

F_fun = matlabFunction(F);

fplot(F_fun)

hold on

plot(xcurrent,F_fun(xcurrent),'o')

F_prime = matlabFunction(diff(F));

N=0;

tolerance = 1.e-6;

while (N < 30) && (abs(xcurrent-xold) > tolerance )

N=N+1;

xold = xcurrent;

xcurrent = xold - F_fun(xold)./F_prime(xold);

plot(xcurrent,F_fun(xcurrent),'o')

end

if(N == 30)

print("Too many iterations");

else

display(xcurrent)

end

That should get the point across, that there is no need to use symbolic tools as heavily as you are.

Erik Ramirez
on 5 Sep 2019

this looks way better!! could i show you my secant method im having trouble with it

Sign in to comment.

Answer by Walter Roberson
on 5 Sep 2019

Erik Ramirez
on 5 Sep 2019

would i use double on just when i printed out?

Walter Roberson
on 5 Sep 2019

display(double(q))

Erik Ramirez
on 5 Sep 2019

YOOOOO THANK YOU SO MUCH!!!!

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.