Module: Philiprehberger::MathKit::Interpolation

Defined in:
lib/philiprehberger/math_kit/interpolation.rb

Class Method Summary collapse

Class Method Details

.linear(points, x) ⇒ Float

Linear interpolation between sorted points

Parameters:

  • points (Array<Array(Numeric, Numeric)>)

    sorted array of [x, y] pairs

  • x (Numeric)

    the x value to interpolate at

Returns:

  • (Float)

    the interpolated y value

Raises:

  • (ArgumentError)

    if fewer than 2 points or x is out of range



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/philiprehberger/math_kit/interpolation.rb', line 13

def linear(points, x)
  raise ArgumentError, 'at least 2 points are required' if points.size < 2

  sorted = points.sort_by(&:first)

  if x <= sorted.first[0]
    return extrapolate(sorted[0], sorted[1], x) if x < sorted.first[0]

    return sorted.first[1].to_f
  end

  if x >= sorted.last[0]
    return extrapolate(sorted[-2], sorted[-1], x) if x > sorted.last[0]

    return sorted.last[1].to_f
  end

  # Find the bracketing pair
  i = sorted.index { |pt| pt[0] >= x }
  return sorted[i][1].to_f if sorted[i][0] == x

  interpolate_between(sorted[i - 1], sorted[i], x)
end