Linear Interpolation

Taneaki Mori



Linear Interpolation code: https://github.com/taneaki/MyInterpolations.jl/blob/master/src/MyInterpolations.jl



1.補間関数



In [3]:
using MyInterpolations

In [4]:
grid =[1, 2, 3, 4, 5, 6, 7, 8]
vals = [2, 0, 4, -1, 3, 7, 3, 10]
f = lin_int(grid,vals)

f.([0,1, 2.7, 7.5, 8.1])


Out[4]:
5-element Array{Any,1}:
  "error"
 2.0     
 2.8     
 6.5     
  "error"


単体テストの実行



In [5]:
Pkg.test("MyInterpolations")


INFO: Testing MyInterpolations
INFO: MyInterpolations tests passed


2.sin関数の線形補間



[-7,7]を10分割した点での補間をまず見てみる。



In [6]:
using Plots
plotlyjs()


Plotly javascript loaded.

To load again call

init_notebook(true)

WARNING: using Plots.grid in module Main conflicts with an existing identifier.
Out[6]:
Plots.PlotlyJSBackend()

In [7]:
x = linspace(-7,7,10)    # x points, coase grid
y = sin.(x)  # corresponding y points

xf = -7:0.1:7  # fine grid
plot(xf, sin.(xf), label="sine function")
plot!(x, y, st=:scatter, label="sampled data", markersize=4)


Out[7]:

In [8]:
li = lin_int(x, y)
y_linear_qe = li.(xf)       # evaluate at multiple points

plot(xf, sin.(xf), label="sine function")
plot!(xf, y_linear_qe, label="linear interpolation")
scatter!(x, y, label="sampled data", markersize=4)


Out[8]:


次に、10,20,30分割した場合の補間とその残差を見てみる。



In [9]:
samples = [10,20,30]
grids = [linspace(-7,7,sample) for sample in samples]
interps = [lin_int(grid, sin.(grid)) for grid in grids]


Out[9]:
3-element Array{MyInterpolations.#func#1{LinSpace{Float64},Array{Float64,1}},1}:
 MyInterpolations.func
 MyInterpolations.func
 MyInterpolations.func

In [10]:
labels1 = Array{String}(1, 3)
for (i, sample) in enumerate(samples)
    labels1[i] = "linear interpolation at $sample times"
end

In [11]:
plot(xf, [interps[i].(xf) for i in 1:3], label = labels1)
plot!(xf, sin.(xf), label = "sine function")


Out[11]:

In [12]:
labels2 = Array{String}(1, 3)
for (i, sample) in enumerate(samples)
    labels2[i] = "residual at $sample times"
end

In [13]:
plot(xf, [sin.(xf) - interps[i].(xf) for i in 1:3], label = labels2)


Out[13]: