Posted By: Anonymous
How do I calculate the derivative of a function, for example
y = x2+1
Let’s say, I want the value of derivative at x = 5…
You have four options
Finite differences require no external tools but are prone to numerical error and, if you’re in a multivariate situation, can take a while.
Symbolic differentiation is ideal if your problem is simple enough. Symbolic methods are getting quite robust these days. SymPy is an excellent project for this that integrates well with NumPy. Look at the autowrap or lambdify functions or check out Jensen’s blogpost about a similar question.
Automatic derivatives are very cool, aren’t prone to numeric errors, but do require some additional libraries (google for this, there are a few good options). This is the most robust but also the most sophisticated/difficult to set up choice. If you’re fine restricting yourself to
numpy syntax then Theano might be a good choice.
Here is an example using SymPy
In : from sympy import * In : import numpy as np In : x = Symbol('x') In : y = x**2 + 1 In : yprime = y.diff(x) In : yprime Out: 2⋅x In : f = lambdify(x, yprime, 'numpy') In : f(np.ones(5)) Out: [ 2. 2. 2. 2. 2.]