Derivative using Interpolations.jl failing

I was trying to compute gradient of the points in the y-variable but it errors out:

using Interpolations
x = 1:6;
y = [1.0,2.0,3.0, 5.0, 10.0, 7.0];

itp = interpolate((x,), y, Gridded(Linear()));
only.(Interpolations.gradient.(Ref(itp), y))

Error:

ERROR: BoundsError: attempt to access 6-element interpolate((::Vector{Int64},), ::Vector{Float64}, Gridded(Linear())) with element type Float64 at index [10.0]
Stacktrace:
  [1] throw_boundserror(A::Interpolations.GriddedInterpolation{Float64, 1, Float64, Gridded{Linear{Throw{OnGrid}}}, Tuple{Vector{Int64}}}, I::Tuple{Float64})
    @ Base ./abstractarray.jl:651
  [2] gradient
    @ ~/.julia/packages/Interpolations/3gTQB/src/gridded/indexing.jl:20 [inlined]
  [3] _broadcast_getindex_evalf
    @ ./broadcast.jl:648 [inlined]
  [4] _broadcast_getindex
    @ ./broadcast.jl:621 [inlined]
  [5] getindex
    @ ./broadcast.jl:575 [inlined]
  [6] macro expansion
    @ ./broadcast.jl:984 [inlined]
  [7] macro expansion
    @ ./simdloop.jl:77 [inlined]
  [8] copyto!
    @ ./broadcast.jl:983 [inlined]
  [9] copyto!
    @ ./broadcast.jl:936 [inlined]
 [10] copy
    @ ./broadcast.jl:908 [inlined]
 [11] materialize(bc::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Nothing, typeof(Interpolations.gradient), Tuple{Base.RefValue{Interpolations.GriddedInterpolation{Float64, 1, Float64, Gridded{Linear{Throw{OnGrid}}}, Tuple{Vector{Int64}}}}, Vector{Float64}}})
    @ Base.Broadcast ./broadcast.jl:883
 [12] top-level scope

You are trying to evaluate an interpolation on a grid ranging from 1 to 6 at the value 10 - ie you are extrapolating rather than interpolating. You need to specify an extrapolation when constructing the interpolant, see the example on the first page of the docs here

https://juliamath.github.io/Interpolations.jl/stable/#Example-Usage

1 Like