Skip to content

Instantly share code, notes, and snippets.

@tbeason
Created September 8, 2017 17:09
Show Gist options
  • Save tbeason/63fc18fb9d70d66a8a6ccf02f2312e1e to your computer and use it in GitHub Desktop.
Save tbeason/63fc18fb9d70d66a8a6ccf02f2312e1e to your computer and use it in GitHub Desktop.
using BenchmarkTools
struct MyType
x::Vector{Float64}
y::Vector{Float64}
_n::UInt16
delta::Vector{Float64}
function (::Type{MyType})(x::Vector{Float64}, y::Vector{Float64})
if size(x, 1) != size(y, 1)
err = "x and y must have same number of elements"
throw(DimenmyonMismatch(err))
end
delta=diff(y)./diff(x)
new(x,y,length(x),delta)
end
end
function MyType(x::AbstractVector{T1}, y::AbstractVector{T2}) where {T1,T2<:Real}
MyType(collect(x), collect(y))
end
function (my::MyType)(xp::T) where {T<:Real}
ix::UInt16 = searchsortedfirst(my.x, xp)
s::Float64 = 0.0
value::Float64 = 0.0
@inbounds begin
if ix==1
s = xp-my.x[1]
value = my.y[1] + s * my.delta[1]
elseif ix==my._n + 1
s = xp-my.x[end]
value = my.y[end] + s * my.delta[end]
else
s = xp-my.x[ix-1]
value = my.y[ix-1] + s * my.delta[ix-1]
end
end
return value
end
function testit()
x = 1.0:0.5:10.5
y = log.(x)
myty = MyType(x,y)
@btime myty(5.0)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment