Interpolate

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
					
public class Program {
  private static double Interpolate(List<(double x, double y)> list, double x) {
    if (list.Count == 0)
      return double.NaN;

    if (list.Count == 1)
      return list[0].y;

    var index = list.BinarySearch((x, 0),
      Comparer<(double x, double y)>.Create((left, right) => left.x.CompareTo(right.x)));

    if (index >= 0)
      return list[index].y;

    int leftIndex = ~index - 1;

    if (leftIndex < 0)
      leftIndex = 0;

    int rightIndex = leftIndex + 1;

    if (rightIndex == list.Count) {
      leftIndex -= 1;
      rightIndex -= 1;
    }

    double xa = list[leftIndex].x;
    double ya = list[leftIndex].y;

    double xb = list[rightIndex].x;
    double yb = list[rightIndex].y;

    return ya + (x - xa) / (xb - xa) * (yb - ya);
  }	
	
  public static void Main()	{
	var data = new List<(double x, double y)> {
      (1, 123),
      (2, 234),
      (3, 345),
    };
	  
	var result = Interpolate(data, 1.5);
	  
	Console.WriteLine(result);
  }
}
;