# Capture an output function

I use the Calculus module in julia to differentiate functions. For example,

``````using Calculus
differentiate("-exp(x)+exp(-x/2)*(2*cos((sqrt(3)/2)*x)+sin((sqrt(3)/2)*x))",:x)
``````

Everything works beautifully. Now I want to define a new function that is the derivative. As of now, I copy and paste the output. That’s not very elegant! What could I do to capture the output? In sage, I can just say “fp(x)=diff(f(x),x)” – looking at other posts, the Base function redirect_stdout may help, but I would need to see an example of how to make it work (and I am not sure it’s implemented in Julia 1.6).

The Calculus package has been around for a long time now and it shows. There are much better packages for differentiation nowadays, so I’d strongly recommend looking at those first.

For numeric differentiation of scalar functions specifically, https://github.com/JuliaDiff/ForwardDiff.jl is what most people use, so you could just define `fp` as `fp(x) = ForwardDiff.derivative(f, x)`. If your `f` turns out to not be automatically differentiable for some reason, e.g. because it’s calling out to C code, https://github.com/JuliaDiff/FiniteDifferences.jl also works very well and is robust to numerical error.

If you need symbolic differentiation, https://github.com/JuliaSymbolics/Symbolics.jl should work well for that. Otherwise, there are also bindings to sympy in https://github.com/JuliaPy/SymPy.jl.

1 Like

Thank you for this. ForwardDiff doesn’t give me the derivative itself, it only evaluates it at a certain point. Symbolics will do the job:

Symbolics.derivative(-exp(x)+exp(-x/2)(2cos((sqrt(3)/2)*x)+sin((sqrt(3)/2)*x)),x)

but the output is even less useful than what Calculus will give me. Symbolic’s output is LaTeX code, so I can’t copy and paste it to define a new function.

You are looking for `build_function`, see Function Building and Compilation (build_function) · Symbolics.jl

It appears to create a function that evaluates it at any point. Is that different from the derivative itself?