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;
xold = inf;
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.
Best Answer