Differentiation without explicit function (np.gradient)

One nice option is to use Interpolations.jl to create a piecewise linear interpolation and then ask for its derivatives:

julia> using Interpolations

julia> x = [1, 2, 4];

julia> y = [1, 2, 3];

julia> itp = interpolate((x,), y, Gridded(Linear()));

You can now use itp to interpolate values:

julia> itp(3.0)
2.5

and compute derivatives:

julia> Interpolations.gradient(itp, 3.0)
1-element StaticArrays.SArray{Tuple{1},Float64,1,1} with indices SOneTo(1):
 0.5

Note that this gives you a gradient vector, but you can get the scalar derivative by taking its only element:

julia> only(Interpolations.gradient(itp, 3.0))
0.5

and you can use broadcasting to get multiple derivatives at different x values:

julia> Interpolations.gradient.(Ref(itp), [1.0, 2.0, 3.0])
3-element Array{StaticArrays.SArray{Tuple{1},Float64,1,1},1}:
 [1.0]
 [1.0]
 [0.5]

or as scalars:

julia> only.(Interpolations.gradient.(Ref(itp), [1.0, 2.0, 3.0]))
3-element Array{Float64,1}:
 1.0
 1.0
 0.5
10 Likes