I am trying to implement L’Hôpital’s rule, and my first naive version looks like this:
using ForwardDiff: derivative
∂(f) = x -> derivative(f,x)
function Hôpital(f,g,a)
fₐ, gₐ = f(a), g(a)
any(isnan.((fₐ,gₐ))) && error("fₐ = $fₐ, gₐ = $gₐ")
r = fₐ / gₐ
@show fₐ, gₐ, r
isnan(r) ? Hôpital(∂(f), ∂(g), a) : r
end
Hôpital(x -> x^10 - 1, x -> x^2 - 1,1.0) # 5.0
Hôpital(exp, x -> x,Inf) # Inf
Hôpital(sin, x -> x^2, 0.0) # Inf
Hôpital(log, x -> x, 0) # -Inf, perfect.
Hôpital(exp, x -> x^2,Inf) # Weirdly doesnt work.
It looks like the second derivative of exp
at infinity is NaN
, while it should be Inf
. Same for x -> x^2
, while it should be 2
.
is there a way to get these derivatives at infinity correct ?
Note: i am not interested in using a package like Scipy to compute limits, but rather to see how far I can go with standard Julia.