Professional Documents
Culture Documents
JanMarch 2016
Solutions to Assignment2
1. SMALLEST ERROR FOR DIFFERENTIATION
Code of smallestErrorDiff.m:
% Three point forward difference formula for finding f'(x) for tan^-1 (x)
% at x=1
x = 1;
h = 10.^[-2:-1:-10];
truediff = 1/(1+x^2);
fcalc = (-atan(x+2*h)+4*atan(x+h)-3*atan(x))./(2*h);
err = abs(truediff - fcalc);
[errmin, idx] = min(err);
disp(['Minimum error = ',num2str(errmin),' at h = ',num2str(h(idx))])
Final Result:
Minimum error = 3.2756e-12 at h = 1e-05
Result is: 1e-5
2. ITERATIVE METHOD FOR CUBE ROOT
Code of myCubeRoot.m:
function [x,n] = myCubeRoot(a,tol)
% Use iterative algorithm to compute cube root of a real number
% Inputs
%
% Outputs
%
%
x
n
x = a/2;
% ----------YOU MAY START EDITING BELOW THIS LINE ---------xNew = 1/2 *(x+(a/x^2));
n =1;
while abs(x - xNew)>tol
x = xNew;
xNew = 1/2 *(x+(a/x^2));
JanMarch 2016
n = n+1;
end
x = xNew;
end
Final Results:
>>[x,n] =
myCubeRoot(15.0,1.0e-4)
x =
2.4662
n =
12
>> [x,n] =
myCubeRoot(8.0,1.0e-2)
x =
2.0029
n =
7
JanMarch 2016
(Last three lines in bold are the statements added as a part of this assignment. The first 12
lines were provided in the template file.)
Final Result:
>> cosVal = maclaurinCos(0.75,4)
cosVal =
0.7319
>> cosVal = maclaurinCos(3.0,9)
cosVal =
-0.9748
the 0 order term, f(2) = 1 + x is 1st order term, and so on. So, the order of exponent is one
less than the size of vector. This is same as what we saw in vec in previous problem.
Code of expMac.m:
% Maclaurin series for exponential
x = -1.2;
f(2) = 1+x;
f(1) = 1;
vec = [1 x];
JanMarch 2016
n = 2;
while ( abs(f(n)- f(n-1))>5e-3)
numerator = x^n;
denom = factorial(n);
vec = [vec, numerator/denom];
f(n+1) = sum(vec);
n = n+1;
end
% The next command is required because f(1) is 0-th order term
n = n-1
expVal = f(end)
Final Result:
>> expMac
n =
6
expVal =
0.3018
result = expVal(n+1)