Plotting a graphical converge inside a While - Newton Raphson numerical method
Afficher commentaires plus anciens
Hi, I'm trying to get a command inside a while so as the Newton Rapshon code shows a graphical converge. If the values of the aproximations are connected between a line, it shows something like a spider web. Can anyone help me out, please?
Here is my code:
clear
clc
syms x
f = input('Introducir la función: '); %function
p0 = input ('Introducir valor semilla: '); %first aproximation
TOL = input ('Introducir la tolerancia de error: '); %error
fplot (f)
grid on
hold on
derivada = diff(f);
derivada = inline (derivada);
f = inline (f);
eabs = 100;
i =0;
while eabs>TOL
p = p0 - (f(p0))/(derivada(p0));
eabs = abs(((p-p0)/p)*100);
p0 = p;
i = i+1;
end
fprintf('\n Valor= %8.3f ',p0)
plot (p)
fplot (0)
hold off
7 commentaires
Walter Roberson
le 26 Août 2019
Is it strictly necessary that the lines be drawn during the execution of the while loop, or could it be drawn after the while finishes?
Luis Francisco Sanchez
le 26 Août 2019
Walter Roberson
le 26 Août 2019
allp = p0;
allfp = [];
while eabs>TOL
fp = f(p0);
p = p0 - fp/(derivada(p0));
eabs = abs(((p-p0)/p)*100);
p0 = p;
i = i+1;
allp(end+1) = p;
allfp(end+1) = fp;
end
plot(allp(1:end-1), allfp);
Luis Francisco Sanchez
le 27 Août 2019
Luis Francisco Sanchez
le 27 Août 2019
Walter Roberson
le 27 Août 2019
p = asin(sin(p));
David Wilson
le 27 Août 2019
Another solution assuming you are looking for an iterative numerial stragegy that stays strictly within the given bounds is to use bisection. Sure it is slow, but it will stay within the -pi/2 to +pi/2 bound.
F = @(x) -x +cos(x)+tan(x); % function of interest
eps = 0.0; tol = 1e-6; % assume some stopping tolerance, set eps to 0.1 if nervous
x = [-pi/2+eps, pi/2-eps];
Fx = F(x); % should be vectorised
assert(prod(sign(Fx)) < 0,'x does not bracket root')
while abs(diff(x)) > tol % Now start bisection routine
m = mean(x); % mid point, m = (a + b)/2
fm = F(m); % find f(m)
if Fx(1)*fm > 0
x(1)=m; Fx(1)=fm; % discard left
else
x(2)=m; % discard right
end % if
end % while
Either value of x is a reasonable solution.
Réponses (0)
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!