How can I code this Newton-Raphson and Secant Methods?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Umut Berkcan Karahan
am 10 Mai 2020
Kommentiert: Muhammad Raihan Ekaputra Idrisatria
am 2 Nov. 2020
Determine the root of the given equation (3*x*e^x)-1=0 for x ∈ [0,1] using Newton-Raphson and Secant methods. Stop calculation after seven iterations. I've coded a code but I'm not sure it is right or not...
%f is non-linear function.
%fder is derivation of f.
%x0 is initial value of iteration.
%e is tolerance of f function.
%d is first condition tolerance value.
%y is error amount.
%max is maximum iteration number.
syms x
x0 = 0;
x1 = 1;
d = 0.000001;
e = 0.00001;
max = 7;
f = @(x) 3*x*exp(x)-1;
fder = @(x) 3*(exp(x)+exp(x))*x;
for iteration = 0:max
t = fder(x0); %to check the derivation is zero or not.
if abs(t)<e
disp('Derivation value is very close to zero, algorithm stops')
break
end
x1 = x0-(f(x0)/fder(x0));
error = abs(x1-x0);
odderror = 2*error/(abs(x1)+d);
x0 = x1;
y = f(x0);
if(error<d)||(odderror<d)||(abs(y)<e)
break
end
end
disp('Wanted root value')
x1
disp('Error amount')
y
disp('Iteration number')
iteration
1 Kommentar
Muhammad Raihan Ekaputra Idrisatria
am 29 Okt. 2020
Use this function that made by me https://www.mathworks.com/matlabcentral/fileexchange/81758-newton-raphson-secant-method
I mixed Newton-Raphson and backward euler to solve the derrivation using numeric method
Akzeptierte Antwort
David Hill
am 10 Mai 2020
The basic code is as follows. You can do other checks as desired.Your code looked ok, except you don't need symbolic variables and your fder function was missing a ')'.
x=0;
f = @(x) 3*x.*exp(x)-1;
fder = @(x) 3*(exp(x)+exp(x).*x);
for k=1:7%newton method
x=x-f(x)/fder(x);
end
y=[0,1];
for k=1:7%secant method
z=y(2);
y(2)=y(2)-f(y(2))*diff(y)/diff(f(y));
y(1)=z;
end
2 Kommentare
Muhammad Raihan Ekaputra Idrisatria
am 2 Nov. 2020
better you add an if condition, if f(x0)=0 then x=x0. To avoid a division by 0
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Symbolic Math Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!