LinearInterpolator { public double evaluate(double value) throws MacroBaseInternalError { if ((value > x[x.length - 1]) || (value < x[0])) { return Double.NaN; } for (int i = 0; i < x.length; i++) { if (value == x[i]) { return y[i]; } if (value >= x[i+1]) { continue; } double dx = x[i+1] - x[i]; double dy = y[i+1] - y[i]; double slope = dy / dx; double intercept = y[i] - x[i] * slope; return slope * value + intercept; } throw new MacroBaseInternalError("Linear interpolator implemented incorrectly"); } LinearInterpolator(double[] x, double[] y); double evaluate(double value);  }
@Test public void testEvaluate() throws Exception { LinearInterpolator interpolator = new LinearInterpolator(x, y); double result; result = interpolator.evaluate(-3); assertEquals(Double.NaN, result, 0.01); result = interpolator.evaluate(-2); assertEquals(1.0, result, 0.01); result = interpolator.evaluate(-1); assertEquals(2.0, result, 0.01); result = interpolator.evaluate(0); assertEquals(3.0, result, 0.01); result = interpolator.evaluate(0.5); assertEquals(3.0, result, 0.01); result = interpolator.evaluate(1); assertEquals(3.0, result, 0.01); result = interpolator.evaluate(1.5); assertEquals(5.0, result, 0.01); result = interpolator.evaluate(3); assertEquals(-1.0, result, 0.01); result = interpolator.evaluate(3.5); assertEquals(Double.NaN, result, 0.01); }