Problem with Newton Raphson Method for Two Variables

22 views (last 30 days)
clc,clear
% Newton Raphson solution of two nonlinear algebraic equations
% set up the iteration
error1 = 1.e8;
xx(1) = 0; % initial guesses
xx(2) = 0.5;
iter=0;
maxiter=40
% begin iteration
while error1>1.e-12
iter=iter+1;
x = xx(1);
y = xx(2);
% calculate the functions
f(1) = 4*x^2-20*x+0.25*y^2+8;
f(2) = 0.5*x*y^2+2*x+8;
% calculate the Jacobian
J(1,1) = 8*x-20;
J(1,2) = 0.5*y;
J(2,1) = 0.5*y^2+2;
J(2,2) = x*y;
% solve the linear equations
y = -J\f';
% move the solution, xx(k+1) - xx(k), to xx(k+1)
xx = xx + y';
% calculate norms
error1=sqrt(y(1)^2+y(2)^2);
error(iter)=sqrt(f(1)^2+f(2)^2);
ii(iter)=iter;
if (iter > maxiter)
error1 = 0;
s=sprintf('****Did not converge within %3.0f iterations.****',maxiter);
disp(s)
end
% check if error1 < 1.e-12
end
x = xx(1);
y = xx(2);
f(1) = 4*x^2-20*x+0.25*y^2+8;
f(2) = 0.5*x*y^2+2*x+8;
% print results
f
xx
iter
% plot results
semilogy(ii,error)
xlabel('iteration number')
ylabel('norm of functions')
clear ii
clear error
What am i doing wron here? It does not converge and can not find the correct values for x and y? are these error equations "% calculate norms error1=sqrt(y(1)^2+y(2)^2); error(iter)=sqrt(f(1)^2+f(2)^2);" right? please help me.

Answers (1)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 27 Nov 2020
close all; clc,clear
% Newton Raphson solution of two nonlinear algebraic equations
xy = [0 1]; % initial guesses
iter=0;
maxiter=40;
xy_N = 1e3;
TOL = 1e-2;
error1 = [1, 1];
f = zeros(iter, 2);
error = zeros(iter, 2);
% begin iteration
while xy_N>TOL
iter=iter+1;
x = xy(1);
y = xy(2);
% calculate the functions
f(iter,:) = [4*x^2-20*x+0.25*y^2+8, 0.5*x*y^2+2*x+8];
% calculate the Jacobian
J= [8*x-20, 0.5*y; 0.5*y^2+2, x*y];
xy_new = xy - ((J)\f(iter,:)')';
error1=abs(xy_new-xy);
error(iter,:)=error1;
% Calculate norm:
xy_N = norm(f(iter,:));
XYN(iter) = xy_N;
xy=xy_new;
%iter=iter+1;
if (iter > maxiter)
fprintf('*** !!! Did not converge within %3.0f iterations!!! \n', maxiter);
break
end
end
if iter<maxiter
f(iter+1:end,:)=[];
end
% Print results
fprintf('Number of iterations is: %f \n ', iter)
fprintf('Final values of [x, y] = %f %f \n', xy(end, :));
fprintf('Final values of EQN: %f %f \n', f(end, :));
fprintf('Final values of ERROR: %f %f \n', error(end, :));
% plot results
semilogy(1:iter,XYN)
xlabel('Iteration number')
ylabel('Norm values'), grid on
title(['Norm values over ' num2str(iter) ' iterations'])
figure
plot(1:iter,f(:, 1)), hold on; plot(1:iter, f(:,2)), grid on;
legend('f_1= 4*x^2-20*x+0.25*y^2+8', 'f_2=0.5*x*y^2+2*x+8')
xlabel('iteration number')
ylabel('Eqn values')

Community Treasure Hunt

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

Start Hunting!