Any coded part should be explained briefly with comments. Divide problems in Pro
ID: 3572150 • Letter: A
Question
Any coded part should be explained briefly with comments. Divide problems in Project3.m into sections with the %% command. Any graphs should contain a title, axes labels, and legend if applicable. All output must be clearly formatted. Answers to questions should be put in comments. Please make the following modifications to your newtonmethod.m and secantmethod.m codes before proceeding with the project: Add a second output variable for the number of steps, if they are not in that format already. Add a fprintf statement to each code to print out the step number and the approximation at each step. Use Newton's Method to approximate the fixed point of the function f(x) = e^-x to an accuracy of 10^-4. Choose any starting value for x0 that gives convergence. Recall, a function f has a fixed point at x whenever f(x) = x, so the above function will need to be rearranged accordingly (i.e. you are NOT solving e^-x = 0). Repeat the problem above using the Secant Method. Use the same x0 from Newton's method in 1(a) and choose a nearby x1. Compare the output of both methods and write your thoughts as comments. function xn = newtonmethod (f, fd, x0, tol) xn=x0; error=abs(f(xn)); i=0; while error>tol i=i+1; xn=xn-f(xn)/fd(xn); error=abs(f(xn)); end function [xn, numiter]=secantmethod(f, x0, x1, tol); %function p=secant(g, p0, p1, tol, nmax); %Function outputs an estimate for the root. Inputs to the code are the % function f, the two initial guesses for the root, p0 and p1, the desired % tolerance for the error, tol, and the maximum number of iterations, nmax. % f(x_n-1) % f(x_n) % x_n-l % x_n %initialize error % initialize counter while err>tol % % increment counter % calculate new x_n % print statement if desired % calculate new error % current x becomes old x % xold is old x_n % new x becomes current x end numiter=i; % if err>tol % fprintf('No root was reached. '); % endExplanation / Answer
script.m
%newton's method
f = @(x) exp(-x) - x;
tol = 0.0001;
x0 = 1;
fd = @(x) -1.0*exp(-x) - 1;
newtonmethod(f,fd,x0,tol);
%secant method
f = @(x) exp(-x) - x;
tol = 0.0001;
x0 = 1;
x1 = 1.1;
secantmethod(f, x0, x1, tol);
secantmethod.m
function [xn, numiter] = secantmethod(f, x0, x1, tol)
err = 1;
i = 0;
while err > tol
i = i + 1;
xn = (x1*f(x1) - x0*f(x0))/(f(x1)-f(x0));
printf('Iteration number: %f xn: %f ', i, x1);
err = xn-x1;
x0 = x1;
x1 = xn;
end
numiter=i;
newtonmethod.m
function xn = newtonmethod(f, fd, x0, tol)
xn = x0;
error = abs(f(xn));
i=0;
while error>tol
i=i+1;
xn = xn-f(xn)/fd(xn);
error = abs(f(xn));
printf('Iteration number: %f xn: %f ', i, xn);
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.