Search code examples
juliasymbolic-mathcalculusdifferentiation

Julia symbolic differentiation


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?


Solution

  • 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.)