Linear Interpolation

Taneaki Mori



Linear Interpolation code: https://github.com/taneaki/Interpolations.jl/blob/master/lin_int.jl



1.補間関数



In [9]:
println(readall(`cmd /c type lin_int.jl`))


function lin_int(grid,vals)
    function func(x)
        if x < grid[1]
            return "error"
        end
        if x > grid[end]
            return "error"
        end
        if x == grid[end]
            return vals[end]
        end
        if grid[1] <= x < length(grid)
            z = searchsortedlast(grid,x)
            slope = (vals[z+1]-vals[z])/(grid[z+1]-grid[z])
            y = slope*(x-grid[z])+vals[z]
        return y
        end
    end
    
    function func{T<:Real}(x::AbstractVector{T})
        n = length(x)
        out = Array(Any, n)
        fill!(out,0.0)
        for i in 1:n
            out[i] = func(x[i])
        end
        return out
    end
    
    return func
end

In [2]:
include("lin_int.jl")


Out[2]:
lin_int (generic function with 1 method)

In [3]:
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[3]:
5-element Array{Any,1}:
  "error"
 2.0     
 2.8     
 6.5     
  "error"


2.残差関数



In [4]:
g(x) = 2 .* cos(6x) .+ sin(14x) .+ 2.5


Out[4]:
g (generic function with 1 method)


線形補間の精度によって残差がどのように変化するかを見てみる。



In [21]:
units = [.25, .2, .1]
grids = [0:unit:1 for unit in units]
interps = [lin_int(grid, g(grid)) for grid in grids]
residuals = [x -> g(x) - interp(x) for interp in interps]
x =(1:99)/100


Out[21]:
0.01:0.01:0.99


3.プロット



頻度の違いによる線形補間の違い。



In [23]:
using PyPlot
plot(x, g(x), label="original function")
for (interp, unit) in zip(interps, units)
    plot(x, interp(x), label="linear interpolation by $(unit)")
end
legend()


Out[23]:
PyObject <matplotlib.legend.Legend object at 0x000000001C1426D8>


頻度の違いによる残差の違い。



In [24]:
using PyPlot
for (residual, unit) in zip(residuals, units)
    plot(x, residual(x), label="by $(unit)")
end
legend()


Out[24]:
PyObject <matplotlib.legend.Legend object at 0x000000001C197DA0>

In [ ]: