Monday, October 1, 2012

L'Hospital Rule in Matlab

As far as I know,Matlab dictionary doesn't contain any special function or command for L'Hospital rule.
So,here I am sharing a small program which can recover the following problem.

As we know


                 
Problem :-

n=[0:7]
x=sin((pi*n)/2)./(pi*n)

Normally it will return,


n =
     0     1     2     3     4     5     6     7

x =
       NaN    0.3183    0.0000   -0.1061   -0.0000    0.0637    0.0000   -0.0455

Solution :-




fderiv = @(f,x) (f(x+eps)-f(x))/eps;                                  % Derivative of a function
xderiv = @(x) ((x+eps)-x)/eps;                                        % Derivative of an expression
for n = 0:7
    x(n+1)=sin((pi*n)/2)./(pi*n)
    if isnan( x(n+1) )                                                           % Test for ‘NaN’
        x(n+1) = (fderiv(@sin, pi*n)/2)./(xderiv(pi*n));      % L'Hospital's Rule
    end
end

It will return the exact answer we want i.e


x =
    0.5000    0.3183    0.0000   -0.1061   -0.0000    0.0637    0.0000   -0.0455


I think this is the simplest program for above problem.
If anyone have some other simple way to solve this problem they can share in comments.


No comments:

Post a Comment