BoundsError -> NaN ? (in Interpolations)

I need a NaN when the target isn’t in the “interior” in linear interpolation:

using Distributions
using Interpolations

const imax_in = 20
const imax_out = 20

xax_in, v_in =
  let dx = rand(Uniform(1.0, 10.0), imax_in)
    f(x) = x - x^3
    xax = [0; cumsum(dx)]
    xax, f.(xax)
  end

xax_out =
  let dx = rand(Uniform(0.5, 20.0), imax_out)
    [2.3; cumsum(dx)]
  end

ip = linear_interpolation(xax_in, v_in)

v_out = ip.(xax_out) #-> BoundsError as expected.

Currently, I get BoundsError of course, but I want NaN values there.

Is there an option to the interpolator to return NaN?


The following is an off-topic question. Are there arrays and dictionaries that return a prescribed values (such as NaN and nothing) instead of throwing BoundsError or KeyError?

This is documented here, i.e.,

ip = linear_interpolation(xax_in, v_in; extrapolation_bc = NaN)

You may also want to check the section on Extrapolation.

PS: For vectors, arrays or dictionaries you can just use get which takes a default argument for out-of-bound keys:

julia> A = reshape(1:6, 2, 3);

julia> get(A, (1, 2), NaN)
3

julia> get(A, (4, 2), NaN)
NaN
2 Likes

Thank you!!

I’ve been using Julia more than a year but still I’m not able to find right documentations . . . Perhaps because Julia is too young, Google search isn’t working for me. Of course I visited the official documentation of Interpolations.jl but somehow I failed to locate the information.

Not just Interpolations but all sorts of Julia packages. I end up asking simple questions whose answers are in the official documentations. . . .

Regarding get(): Thank you for that, too!

It’s strange that I’ve never heard of such a fundamental function as that. I’ve sometimes used getindex( ) as a function form of [ ], but get() seems to be more fundamental (generic) than getindex(). For one thing, getindex(A, 4, 2) could be realized as get(A, (4,2); outofrange=Throw()) (mimicking linear_interpolation()). I mean that getindex() could be viewed as a special case of get(), but not the other way round.