solve eq by newton raphson method
1 view (last 30 days)
Show older comments
i want to write a script that will calculate for solution of equation :
3x+sin(x)-exp(x)=0
with Newton Raphsons method algorithm.
Answers (1)
Radu Trimbitas
on 20 Jan 2022
Solve the equation
with Newton-Raphson method.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/868210/image.png)
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 Comments
See Also
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!