Determining the natural logrithim of a number p lnp is the s
Determining the natural logrithim of a number p, ln(p), is the same as finding a solution to the equation f(x) = (e^x) - p = 0 . Wrinte a MATLAB user-defined function tht determines the natural logarithm of a number by solving the equation using the bisection method. Name the function X = Ln(p). The output argument X is the value of ln(p), and the input argument p is the number whose natural logarithm is determined. The program should include the following features:
* The starting values of a and b are a = 0 and b = p, respectively if b > exp(1), and a = -1/p and b = exp(0), respectively, if b < exp(1).
*The iterations should stop when the tolerance is smaller than 1x10^-6
*The number of iterations should be limited to 100. If a solution is not obtained in 100 iterations, the function stops and displays an error message.
* If zero or a negative number is entered for p, the program stops and displays an error message.
Use the function Ln to determine the natural logarithm of (a)510....(b)1.35.....(c)1......(d)7
Solution
%Matlab code here
function [ X ] = Ln( p )
%LN Summary of this function goes here
% Detailed explanation goes here
% Check that that neither end-point is a root
if p<=0
error( \'logarithm doesnt exit for 0 or negative number\' );
end
eps_step=1e-6;% tolerance
eps_abs=1e-6;% tolerance
f=@(x) exp(x)-p; %function whose root to be found
a=0;
b=p;
% and if f(a) and f(b) have the same sign, throw an exception.
if ( f(a) == 0 )
X = a;
return;
elseif ( f(b) == 0 )
X = b;
return;
elseif ( f(a) * f(b) > 0 )
error( \'f(a) and f(b) do not have opposite signs\' );
end
% We will iterate N times and if a root was not
% found after N iterations, an exception will be thrown.
N=100; % as given iteration limited to 100
for k = 1:N
% Find the mid-point
c = (a + b)/2;
% Check if we found a root or whether or not
% we should continue with:
% [a, c] if f(a) and f(c) have opposite signs, or
% [c, b] if f(c) and f(b) have opposite signs.
if ( f(c) == 0 )
X = c;
return;
elseif ( f(c)*f(a) < 0 )
b = c;
else
a = c;
end
% If |b - a| < eps_step, check whether or not
% |f(a)| < |f(b)| and |f(a)| < eps_abs and return \'a\', or
% |f(b)| < eps_abs and return \'b\'.
if ( b - a < eps_step )
if ( abs( f(a) ) < abs( f(b) ) && abs( f(a) ) < eps_abs )
X = a;
return;
elseif ( abs( f(b) ) < eps_abs )
X = b;
return;
end
end
end
error( \'the method did not converge\' );
end
%------------------------------------------------------------------------
Results
>> Ln(510)
ans =
6.2344
>> Ln(1.35)
ans =
0.3001
>> Ln(1)
ans =
0
>> Ln(7)
ans =
1.9459

