Creating L'hopital's rule - WITHOUT the Limit command?
1 view (last 30 days)
Show older comments
Hello, all.
For a recent assignment, I need to create a new function m-file - mylhopital(f,g,a) that will duplicate L'hopital's rule, only without any use of the LIMIT command. In this case, f and g are function handles, while a is the value that x approaches.
The assignment instructs me to calculate the limit of each case by writing a WHILE program that will replace f with f' and g with g' every time f(a) and g(a) equal 0, until f(a) and g(a) have taken on non-zero values.
What code I've written so far (with countless different permutations) is as follows:
function j=mylhopital(f,g,a)
syms x
while (f(a)==0 && g(a)==0)
f(a)=diff(f(x),x,a);
g(a)=diff(g(x),x,a);
end
j=f(a)/g(a);
end
I foolishly thought that this was fine, but it's only fine for samples of (f,g,a) that don't boil down to 0/0 in the first place. When I try to execute mylhopital(@(x)sin(x),@(x)x,0) or mylhopital(@(x)2-2*cos(3*x),@(x)x^2,0), the entire thing blows up and Matlab tells me that I have too many output arguments.
0 Comments
Accepted Answer
Star Strider
on 11 Aug 2014
You don’t need symbolics.
Example:
mylhopital = @(f,g,a) (f(a+1E-8)-f(a)) ./ (g(a+1E-8)-g(a));
% sin(x)/x:
xf = @(x) x;
Lh1 = mylhopital(@(x)sin(x), xf, 0)
% 2-2*cos(3*x)/x^2
Lh2 = mylhopital(@(x)2-2*cos(3*x), @(x)x^2, 0)
produces:
Lh1 =
1.0000e+000
Lh2 =
8.8818e+000
4 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!