In: Advanced Math
Matlab
Consider f(x) = x^3 - x. Plot it. (a) Use Newton's method with p_0 =1.5 to find an approximation to a root with tolerance TOL = 0.01. (b) Use secant method with p_0 = 0.5 , p_1 =1.5, to answer same question as (a). (c) Use Method of False position with initial approximate roots as in (b).
MATLAB Script:
close all
clear
clc
syms x
f = x^3 - x; % f(x)
fd = diff(f); % f'(x)
tol = 1e-2;
% Plotting f(x)
xx = -2:0.01:2;
ff = subs(f, xx);
plot(xx,ff), xlabel('x'), ylabel('f(x)'), grid on
ic = 1.5;
[result] = my_newton(f,fd,ic,tol);
fprintf('Solution (Using Newton''s Method): %.8f\n', result)
a = 0.5; b = 1.5;
result = my_secant(f,a,b,tol);
fprintf('Solution (Using Secant Method): %.8f\n', result)
result = my_false_position(f,a,b,tol);
fprintf('Solution (Using False-Position Method): %.8f\n',
result)
function [res] = my_newton(func,func_d,ic,tol)
res = ic;
while true
x_ = res;
res = res - subs(func, res)/subs(func_d, res);
if abs(x_ - res) < tol
break;
end
end
end
function xc = my_secant(f,a,b,tol)
x = [a b];
while true
x = [x double((x(end-1)*subs(f,x(end)) - x(end)*subs(f,x(end-1))) /
(subs(f,x(end)) - subs(f,x(end-1))))];
if abs(subs(f,x(end))) < tol
break
end
end
xc = double(x(end));
end
function xc = my_false_position(f,a,b,tol)
while true
c = (b*subs(f,a) - a*subs(f,b)) / (subs(f,a) - subs(f,b));
if abs(subs(f,c)) < tol
break
end
if subs(f,a)*subs(f,c) < 0
b = c;
else
a = c;
end
end
xc = double(c);
end
Plot:
Output:
Solution (Using Newton's Method): 1.00000317
Solution (Using Secant Method): 1.00249467
Solution (Using False-Position Method): 0.99736902