Plotting a graphical converge inside a While - Newton Raphson numerical method

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

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?
It's not necessary. I just need the spider web to be drawn over the original graph.
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);
Thank you very much, Walter. Works perfectly
I have another question. I'm solving an exercise where I need to find the f(x) = 0 of the funciton:
0 = -x +cos(x)+tan(x), since is a periodical graph with multiple y=0, how can I make the code and graph look into a specific range of x? I got {-pi/2,pi/2} as the range of the exercise above
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.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Mathematics dans Centre d'aide et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by