Newton's method iterations

조회 수: 13 (최근 30일)
James Holden
James Holden 2021년 10월 1일
댓글: Alan Stevens 2021년 10월 4일
I have a code written for Netwon's method below. However, not all initial starting guesses would converge. How would I find out which initial values for x would converge for the function in, say 20 or 30 or 50 iterations? For example, I'll start with x0 = 0. Does this converge? Then I'll try x0 = 0.1. Does this converge? The x0 = 0.2, then 0.3, etc. Which ones would converge?
I am trying to figure out how to summarize this information in a table. Below is the code that I have so far for Newton's Method.
%Newton's Method x0 = 7
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 = 7;
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)

답변 (2개)

Alan Stevens
Alan Stevens 2021년 10월 1일
I suggest you plot a graph of your function, then you can see where good initial estimates would be. For example
f = @(x) 2*exp(-2*x) + 4*sin(x) - 2*cos(2*x);
x = 0:0.1:20;
y = f(x);
plot(x,y),grid
  댓글 수: 6
James Holden
James Holden 2021년 10월 3일
Thank you so much. That's almost exactly what I was looking for. Is there a way now to add all my fe values to the table as well? I tried
if abs(fe) <= tol
cv = cv + 1;
c(cv,:,:) = [x0(j), n, fe];
else
fv = fv + 1;
F(fv, 1) = x0(j);
end
but it's telling me that it couldn't perform the assignment because the size of the left is 1-by-2 where the size of the right is 1-by-3. Is the
c(cv,:,:)
part right to set up three collumns instead of just two?
Alan Stevens
Alan Stevens 2021년 10월 4일
Try this
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 = 0.1:0.1:8;
cv = 0; fv = 0;
N = 10;
tol = 1e-6;
for j = 1:numel(x0)
x = x0(j);
n = 0;
fe = 1;
while (abs(fe) > tol) && (n <= N)
n = n+1;
fe = f(x);
fpe = fp(x);
x = x - fe/fpe;
end
if abs(fe)<=tol
cv=cv+1;
feval1(cv,1) = fe;
C(cv,:) = [x0(j), n];
else
fv = fv+1;
feval2(fv,1) = fe;
F(fv,1) = x0(j);
end
end
format shorte
if cv>0
disp('Converged')
disp('[x0, n, fe]')
disp([C, feval1])
end
disp(' ')
if fv>0
disp(['Failed to converge in ' num2str(N) ' iterations'])
disp('x0, fe')
disp([F, feval2])
end

댓글을 달려면 로그인하십시오.


Matt J
Matt J 2021년 10월 3일

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by