Controlling error and conditionsl statement Write a wellcomm
Controlling error and conditionsl statement
Write a well-commented MATLAB function program to do Newton\'s method for a function f until |f(x)| Solution
newt.m
function [x]=newt(f,df,x0,tol)
% input:
% f = name of function
% df = name of derivative of function
% x0 = initial guess
% tol = desired relative error (default = 0.0001%)
% output:
% x = real root
if nargin < 3,
error(\'at least 3 input arguments required\');
end
if nargin < 4|isempty(tol),
tol = 0.0001;
end
xnew = x0; ynew = f(xnew); yp = df(xnew);
while norm(ynew)>10e-7
xnew = xnew - f(xnew)/df(xnew);
ynew = f(xnew);
end
x = xnew;
Output:-
>> ynew = @(m) sqrt(9.81*m/0.25)*tanh(sqrt(9.81*0.25/m)*4)-36;
>> dy = @(m) 1/2*sqrt(9.81/(m*0.25))*tanh((9.81*0.25/m)^(1/2)*4)-9.81/(2*m)*sech(sqrt(9.81*0.25/m)*4)^2;
>> newt(ynew,dy,140,0.00001)
ans = 142.7376
