Why is my newton method giving me a huge answer? What am i doing wrong?pls help
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
Erik Ramirez
am 5 Sep. 2019
Bearbeitet: Rena Berman
am 19 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
0 Kommentare
Akzeptierte Antwort
John D'Errico
am 5 Sep. 2019
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.
Weitere Antworten (1)
Walter Roberson
am 5 Sep. 2019
Your code is not giving you a huge answer: it is giving you a rational answer. You will want to use double() to convert it to floating point.
3 Kommentare
Siehe auch
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!