Capture an output function

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

using Calculus

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, 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, also works very well and is robust to numerical error.

If you need symbolic differentiation, should work well for that. Otherwise, there are also bindings to sympy in

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:


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?