Skip to content

Instantly share code, notes, and snippets.

@ignisf
Created November 21, 2013 01:14
Show Gist options
  • Save ignisf/7574328 to your computer and use it in GitHub Desktop.
Save ignisf/7574328 to your computer and use it in GitHub Desktop.
Lagrange interpolation w/ Barycentric formula
class Barycentric
attr_reader :x, :y
def initialize(samples)
@x = samples.map(&:first).map(&:to_r)
@y = samples.map(&:last).map(&:to_r)
@w = @x.each_index.map { |j| w(j) }
end
def L(x)
return @y[@x.index(x)] if @x.include? x
l(x) * @x.each_index.map { |j| @w[j] * @y[j] / (x - @x[j]) }.reduce(:+)
end
def q
@w
end
private
def l(x)
@x.each_index.map { |i| x - @x[i] }.reduce(:*)
end
def w(j)
@x.each_index.map { |i| 1 / (@x[j] - @x[i]) unless i == j }.compact.reduce(:*)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment