線形補間

瀧川英輝


In [1]:
#Pkg.clone("https://github.com/EikiTakigawa/MyInterpolations.jl")
using MyInterpolations

ソースコードはこちら

まずは課題の説明で書かれていた簡単な例で試してみます


In [4]:
grid = [1, 2]
vals = [2, 0]
f = MyLinInterp(grid, vals)
f(1.25)


Out[4]:
1.5

これは問題なさそうです。次にテストを実行してみます


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


INFO: Testing MyInterpolations
INFO: MyInterpolations tests passed

なぜかTest summaryが表示されませんが、テストは通りました

それではQuantEconの図を再現してみます


In [8]:
using Plots
plotlyjs()

x = -7:7    # x points, coase grid
y = sin.(x)  # corresponding y points

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


Plotly javascript loaded.

To load again call

init_notebook(true)

WARNING: using Plots.grid in module Main conflicts with an existing identifier.
Out[8]:

In [9]:
#li = LinInterp(x, y)        # create LinInterp object
li = MyLinInterp(x, y)        # この部分を自分が作ったものに置き換えています
y_linear_qe = li.(xf)       # evaluate at multiple points

plot(xf, y_linear_qe, label="linear")
scatter!(x, y, label="sampled data", markersize=4)


Out[9]:

うまく再現できました
下の図では、(-7,7)を幅1で区切ったものをgridとしています。
より細かい刻み幅にしたら、真の関数と補間の残差はどうなるか調べてみます


In [10]:
units = [1, 0.5, 0.2]
grids = [-7:unit:7 for unit in units]
interps = [MyLinInterp(grid, sin.(grid)) for grid in grids]


Out[10]:
3-element Array{MyInterpolations.MyLinInterp,1}:
 MyInterpolations.MyLinInterp(-7.0:1.0:7.0,[-0.656987,0.279415,0.958924,0.756802,-0.14112,-0.909297,-0.841471,0.0,0.841471,0.909297,0.14112,-0.756802,-0.958924,-0.279415,0.656987])                                                             
 MyInterpolations.MyLinInterp(-7.0:0.5:7.0,[-0.656987,-0.21512,0.279415,0.70554,0.958924,0.97753,0.756802,0.350783,-0.14112,-0.598472  …  0.598472,0.14112,-0.350783,-0.756802,-0.97753,-0.958924,-0.70554,-0.279415,0.21512,0.656987])          
 MyInterpolations.MyLinInterp(-7.0:0.2:7.0,[-0.656987,-0.494113,-0.311541,-0.116549,0.0830894,0.279415,0.464602,0.631267,0.772764,0.883455  …  -0.883455,-0.772764,-0.631267,-0.464602,-0.279415,-0.0830894,0.116549,0.311541,0.494113,0.656987])

In [13]:
labels = Array{String}(1, 3)
for (i, unit) in enumerate(units)
    labels[i] = "residuals by $unit"
end

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


Out[14]:

これを見る限りgridを細かくとれば、残差は減ってくれそうです


In [ ]: