function [x,it]=newton(fun,dfun,x0,tol,maxit,par) %[x,it]=newton(fun,dfun,x0,tol,maxit) %izracuna niclo funkcije 'fun', ki je 'najblizja' zacetnemu priblizku %'x0'. Newtonova metoda poleg funkcije 'fun' potrebuje tudi %funkcijo, ki izracuna njen odvod 'dfun'. %Niclo izracuna na 'tol' natancno. 'maxit' je spremenljivkam ki omeji %stevilo iteracij (za primer, da Newtonova iteracija ne bi konvergirala) %Poleg priblizka za niclo 'x' funkcija vrne tudi stevilo iteracij 'it', ki %je bilo potrebno. %[x,it]=newton(fun,dfun,x0,tol,maxit) %computes the solution to the equation %fun(x)=0 %using Newton iteration with initial approximation 'x0' %'dfun' is the derivative of the function 'fun' %The Newton iteration terminates when the difference between two %approximations falls below 'tol' or the number of iterations exceeds the %maximum allowed number maxit x=x0;%zacetni priblizek / initial approximation napaka=2*tol;%zacetna napaka / initial value for 'napaka' (error) it=1;%t=stevec iteracij / iteration counter while (napaka>tol)&&(maxit>it)%iteracij poteka dokler ne dosezemo zeljeno natancnost %ali presezemo maksimalno dovoljeno stevilo iteracij % / the iteration continues until we acheive the desired accuracy or %exceed the maximum number of iterations x0=x; y=feval(fun,x,par); dy=feval(dfun,x,par); x=x-dy\y;%bistveni korak Newtonove iteracij / Newtons iteration it=it+1; napaka=norm(x-x0,2);%za napako vzamemo razliko med zaporednima priblizkoma %/ for the error we take the difference of two succesive approximations end