In: Advanced Math
Use MATLAB to figure out the following problem, if you do not know how to use MATLAB then please do not answer. Coding is required for the exercise.
For f(x) = arctan(x), find its zeros by implimenting Newtons method and the Secant method in Matlab. (Hint: Use Newtons method to calculate x1 for Secant method)
Comment all code please since I would like to learn how to do this correctly in MATLAB. Thank you.
MATLAB Script:
close all
clear
clc
syms x
tol = 1e-3; % Error tolerance
f = atan(x); % Given function f(x)
df = diff(f); % f'(x)
% Plot the function to get initial estimates of the roots
x_vals = -5:0.001:5; % Range [-5, 5] with step size of 0.001
f_vals = subs(f, x_vals); % Evaluate f(x) at x = x_vals
plot(x_vals, f_vals), grid on % Plot f(x) and turn on the
gridlines
xlabel('x'), ylabel('f(x)') % Label the axes
title('f(x) = atan(x)') % Add a title
% Newton's method
x0 = -1; % Initial guess
result = newton(f, df, x0, tol);
fprintf('Root (using Newton''s method), x = %.3f\n', result)
% Secant method
x1 = double(x0 - subs(f, x0)/subs(df, x0)); % Apply Newton update
rule to find x1
result = secant(f, x0, x1, tol);
fprintf('Root (using secant method), x = %.3f\n', result)
function x = newton(f, df, x0, tol)
x = x0;
while true
x_ = x; % Save previous iteration's result
x = double(x - subs(f, x)/subs(df, x)); % Newton Update Rule
if abs(x_ - x) < tol % Termination condition
break;
end
end
end
function x = secant(f, a, b, tol)
x = [a b];
while true
xl = x(end-1); xu = x(end);
y = ( xl*subs(f, xu) - xu*subs(f, xl) ) / (subs(f, xu) - subs(f,
xl)); % Secant method's root update
x = [x y];
if abs(x(end-1) - x(end)) < tol % Termination condition
break
end
end
x = x(end);
end
Plot:
Output:
Root (using Newton's method), x = 0.000
Root (using secant method), x = 0.000