Reputation: 170
Though I've looked through several pages documenting various differentiation tools in Julia, I have yet to find the following simple functionality. I want to define a function which is differentiable by hand, e.g, f(x) = 2x.^3
, then call a symbolic computation function to obtain fprime = derivative(f)
. This code should produce the same results as fprime(x) = 6x.^2
. Is there a library function which acts like the made-up function derivative
above?
Upvotes: 2
Views: 1795
Reputation: 1058
There are various packages for automatic differentiation (AD) in Julia. For a single-variable function like the one you describe, the simplest and fastest is probably the ForwardDiff package, which lets you do:
using ForwardDiff
fprime(x) = ForwardDiff.derivative(f, x)
ForwardDiff and other AD packages indeed compute the exact analytical derivative, equivalent to the 6x^2
you might write by hand. (However, the algorithms are a bit different from the "form a big symbolic expression then differentiate" that you might imagine.)
Upvotes: 1
Reputation: 42244
If you work numerically with symbolic derivatives you can also use code-to-code symbolic differentiation by using Zygote
Assume you have f(x) = 2x^3
than having Zygote loaded you can do
julia> f'(5)
150.0
to understand what just happened peek into the compilation process to see that the function f
has been actually symbolically differentiated.
julia> @code_llvm f'(5)
define double @"julia_#79_991"(i64 signext %0) #0 {
top:
%1 = mul i64 %0, 3
%2 = mul i64 %1, %0
%3 = sitofp i64 %2 to double
%4 = fmul double %3, 2.000000e+00
ret double %4
}
Upvotes: 1
Reputation: 310
The Symbolics.jl
package is capable of what you're looking for, although you need to explicitly declare what your variables are
In [2]: using Symbolics
In [3]: @variables x
Out[3]: 1-element Vector{Num}:
x
In [4]: D = Differential(x)
Out[4]: (::Differential) (generic function with 2 methods)
In [5]: f(t) = 2*t^3
Out[5]: f (generic function with 1 method)
In [6]: expand_derivatives(D(f(x)))
Out[6]: 6(x^2)
You can read more about it here: https://symbolics.juliasymbolics.org/dev/manual/derivatives/
Upvotes: 2