LogLog Plots for Newton's and Secant Methods
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
I need help with creating loglog plots for Newton's and the secant method for root approximations in numerical analysis. Here is my Newton's method code that gives a table of the iterations and plots what they converge to.
%Newton's Method x0 = 2.5
f = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
fp = @(x) 4*(-exp(-2*x) + sin(2*x) + cos(x));
x0 = 2.5;
N = 10;
tol = 1E-6;
x(1) = x0;
n = 2;
nfinal = N + 1;
while (n <= N + 1)
fe = f(x(n - 1));
fpe = fp(x(n - 1));
x(n) = x(n - 1) - fe/fpe;
if (abs(fe) <= tol)
nfinal = n;
break;
end
n = n + 1;
end
plot(0:nfinal - 1,x(1:nfinal),'o-')
title('Solution:')
xlabel('Iterations')
ylabel('X')
table([1:length(x)]',x')
x(n) = x(n - 1) - fe/fpe;
fprintf('%3d: %20g %20g\n', n, x(n), abs(fe));
if (abs(fe) <= tol)
And here is my secant method code that just lists the iterations and their values in a table.
%Secant Method x0 = 2.5, x1 = 2.4
func = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
x1 = 2.5;
x2 = 2.4;
tol = 1e-9;
f1 = func(x1);
dx = inf;
iter = 0;
dispdata = [iter;x1;x2]
while abs(dx) > tol
iter = iter + 1;
f2 = func(x2);
dx = (x2 - x1)*f2/(f2 - f1);
x1 = x2;
f1 = f2;
x2 = x2 - dx;
dispdata(:, iter + 1) = [iter;x1;x2];
end
fprintf(" k: x1 x2\n")
fprintf("---------------------------\n")
fprintf("%2d: %7.4f %7.4f\n", dispdata)
How would I go about creating loglog plots for both of these methods? I know that I would use the log log command and really all I am doing is taking the log of the Yn values and the log of the Xn values and plotting the against each other to get a line. The slope of this line would then indicate the rate of convergance. I just dont know the syntax of how I should write the code to do this in MatLab.
0 comentarios
Respuestas (1)
Mathieu NOE
el 1 de Oct. de 2021
hello
here the first code now showing the regular linear plot and a loglog plot
I changed the N to 100 and tol to 1e-20 to have more iterations , but I am not convinced that the loglog plot do have any advantage over the linear plot - your decision
%Newton's Method x0 = 2.5
f = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
fp = @(x) 4*(-exp(-2*x) + sin(2*x) + cos(x));
x0 = 2.5;
N = 100;
tol = 1E-20;
x(1) = x0;
n = 2;
nfinal = N + 1;
while (n <= N + 1)
fe = f(x(n - 1));
fpe = fp(x(n - 1));
x(n) = x(n - 1) - fe/fpe;
if (abs(fe) <= tol)
nfinal = n;
break;
end
n = n + 1;
end
figure,plot(1:nfinal,x(1:nfinal),'o-')
figure,loglog(1:nfinal,x(1:nfinal),'o-')
title('Solution:')
xlabel('Iterations')
ylabel('X')
table([1:length(x)]',x')
x(n) = x(n - 1) - fe/fpe;
fprintf('%3d: %20g %20g\n', n, x(n), abs(fe));
2 comentarios
Ver también
Categorías
Más información sobre Vector Fields en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!