solve eq by newton raphson method

2 visualizaciones (últimos 30 días)
afrah aziz
afrah aziz el 20 de Dic. de 2020
Respondida: Radu Trimbitas el 20 de En. de 2022
i want to write a script that will calculate for solution of equation :
3x+sin(x)-exp(x)=0
with Newton Raphsons method algorithm.

Respuestas (1)

Radu Trimbitas
Radu Trimbitas el 20 de En. de 2022
Solve the equation with Newton-Raphson method.
Define function and derivative
format long
f=@(x) 3*x+sin(x)-exp(x);
df=@(x) 3+cos(x)-exp(x);
Explore the roots graphically
fplot(f,[-pi,pi])
grid on
Find a solution within [0,1]
x0=0;
[z1,ni]=Newton(f,df,x0,1e-8,1e-8,20)
Find a solution within [1,2]
x0=1.5;
[z2,ni]=Newton(f,df,x0,1e-8,1e-8,20)
Check the roots
f([z1,z2])
Code for Newton-Raphson method. It also works for nonlinear systems.
function [z,ni]=Newton(f,fd,x0,ea,er,nmax)
%NEWTON - Newton ethod for nonlinear equations and systems
%call [z,ni]=Newton(f,fd,x0,ea,er,nmax)
%Input
%f - function
%fd - derivative or Jacobian
%x0 - starting value or vector
%ea - absolute error
%er - relative error
%nmax - maximum # iterations
%Iesire
%z - approximate root
%ni - actual # iterations
if nargin < 6, nmax=50; end
if nargin < 5, er=0; end
if nargin < 4, ea=1e-3; end
xp=x0(:); %x precedent
for k=1:nmax
xc=xp-fd(xp)\f(xp);
if norm(xc-xp,inf)<ea+er*norm(xc,inf)
z=xc; %success
ni=k;
return
end
xp=xc;
end
error('Iterations # exceeded');
end

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by