solve eq by newton raphson method
조회 수: 2 (최근 30일)
이전 댓글 표시
i want to write a script that will calculate for solution of equation :
3x+sin(x)-exp(x)=0
with Newton Raphsons method algorithm.
답변 (1개)
Radu Trimbitas
2022년 1월 20일
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
댓글 수: 0
참고 항목
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!