Newton's method - how to make the computational performance faster?
Afficher commentaires plus anciens
I have used a while loop in the algorithm. Once the absolute error is less than the specified tolerance (tol), the while loop stops and the function is expected to output one solution, even though many solutions exist. I have tried x^3 + 8x -18=0 with a starting guess 2. It should take two iterations to obtain the solution, but I cannot figure out why the computational perfomance is very slow when executing the function.
function moisolver
syms x
func=input('Enter the function f(x) which is equal zero:');
xn=input('Enter your initial guess:');
% The function func is switched to a function handle class
Dfunc=jacobian(func,x);
Dfunc=matlabFunction(Dfunc);
% The derivative dfuncd is switched to a function handle class
dfuncd=diff(func);
Dfuncd=jacobian(dfuncd,x);
Dfuncd=matlabFunction(Dfuncd);
% The tolerance is defined. The abs_error, counter and the vector
% storing the approximated solutions during the iteration process, are
% initialized
tol=10^(-1);
abs_error=1;
counter=1;
vec=xn;
while abs_error>=tol
counter=1+counter;
% xn is the iterative solution
xn=xn-Dfunc(xn)/Dfuncd(xn);
% An expanding vector veczero is added with xn
veczero=zeros(1,counter)+xn;
% The former solutions are redefined in veczero. Notice that the
% last element in veczero is defined as the last obtained solution
veczero(1:counter-1)=vec;
% vec is redefined
vec=veczero;
% The absolute error is calculated
abs_error=abs(vec(end)-vec(end-1));
end
solution=vec(end);
fprintf('The solution is %.2f.\n',solution)
fprintf('The computer generated %d iterations to obtain the solution.\n',counter)
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Loops and Conditional Statements dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!