Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function newton(f,df,x0,tol,Nmax)
- syms x;%Setting x to be a symbolic variable
- %Defining the variables
- %f=input('Enter your function here: ');
- %df=input('Enter your differentiated function here: ');
- %x0=input('Enter your initial estimation (if unknown, set as 0): ');
- %Nmax=input('Enter your max number of iterations here ');
- %tol=input('Enter your tolerance ');
- err=tol+1; %Sets error as larger than the tol to initiate the while loop
- n=0; %Creates the iteration counter
- if df==0;
- error('The differential of your function is 0, therefore iterations cannot begin.')
- end
- while err>tol;
- n=n+1;
- fv=subs(f,x,x0);
- fdv=subs(df,x,x0);
- x1=x0-((fv)/fdv);
- err=abs(x1-x0);
- x0=x1;
- if n>Nmax;
- error('The maximum number of iterations has been reached, therefore a solution has not been found.');
- end
- if err<tol;
- break
- end
- end
- fprintf('The root of your function is: %g \n', x0)
- fprintf('This took %d iterations to reach', n)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement