logo

Numerical Interpolation in Julia 📂Julia

Numerical Interpolation in Julia

Overview

In Julia, the Interpolations.jl package is used for numerical interpolation1. Be cautious not to confuse it with the interpolation method used when printing the value of a variable in Julia[../2041].

Code

Interpolate()

julia> y = rand(10)
10-element Vector{Float64}:
 0.8993801321974316
 0.12988982511901515
 0.49781160399025925
 0.22555299914088356
 0.4848674643768577
 0.6089318286915111
 0.10444895196527337
 0.5921775799940143
 0.2149546302906653
 0.32749334953170317

julia> f = interpolate(y, BSpline(Linear()));

julia> f(1.2)
0.7454820707817483

julia> f(0.1)
ERROR: BoundsError: attempt to access 10-element interpolate(::Vector{Float64}, BSpline(Linear())) with element type Float64 at index [0.1]

Basically, as shown above, you can receive the interpolation function f=$f$ itself by giving data and use it. The example shows how a value (0.745) around 1.2 between the 1st (0.899) and 2nd (0.129) given points is interpolated. Refer to the API section of the official documentation to determine the specific method to use2.

linear_interpolation()

x = 1:10

f_lin = linear_interpolation(x, y);
scatter(x, y, label = "Data"); plot!(1:0.01:10, f_lin.(1:0.01:10), label = "Linear")

plot_1.svg

cubic_spline_interpolation()

f_cub = cubic_spline_interpolation(x, y);
scatter(x, y, label = "Data"); plot!(1:0.01:10, f_cub.(1:0.01:10), label = "Cubic")

plot_2.svg

constant_interpolation()

f_con = constant_interpolation(x, y);
scatter(x, y, label = "Data"); plot!(1:0.01:10, f_con.(1:0.01:10), label = "Constant")

plot_3.svg

Full Code

using Interpolations, Plots

y = rand(10)
f = interpolate(y, BSpline(Linear()));
f(1.2)
f(0.1)

x = 1:10

f_lin = linear_interpolation(x, y);
scatter(x, y, label = "Data"); plot!(1:0.01:10, f_lin.(1:0.01:10), label = "Linear")

f_cub = cubic_spline_interpolation(x, y);
scatter(x, y, label = "Data"); plot!(1:0.01:10, f_cub.(1:0.01:10), label = "Cubic")

f_con = constant_interpolation(x, y);
scatter(x, y, label = "Data"); plot!(1:0.01:10, f_con.(1:0.01:10), label = "Constant")

Environment

  • OS: Windows
  • julia: v1.8.5