1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.math4.legacy.analysis.interpolation;
18
19 import org.apache.commons.math4.legacy.analysis.polynomials.PolynomialFunction;
20 import org.apache.commons.math4.legacy.analysis.polynomials.PolynomialSplineFunction;
21 import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
22 import org.apache.commons.math4.legacy.exception.NonMonotonicSequenceException;
23 import org.apache.commons.math4.legacy.exception.NumberIsTooSmallException;
24 import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
25 import org.apache.commons.math4.legacy.core.MathArrays;
26
27
28
29
30
31 public class LinearInterpolator implements UnivariateInterpolator {
32
33
34
35
36
37
38
39
40
41
42
43
44
45 @Override
46 public PolynomialSplineFunction interpolate(double[] x, double[] y)
47 throws DimensionMismatchException,
48 NumberIsTooSmallException,
49 NonMonotonicSequenceException {
50 if (x.length != y.length) {
51 throw new DimensionMismatchException(x.length, y.length);
52 }
53
54 if (x.length < 2) {
55 throw new NumberIsTooSmallException(LocalizedFormats.NUMBER_OF_POINTS,
56 x.length, 2, true);
57 }
58
59
60 int n = x.length - 1;
61
62 MathArrays.checkOrder(x);
63
64
65 final double[] m = new double[n];
66 for (int i = 0; i < n; i++) {
67 m[i] = (y[i + 1] - y[i]) / (x[i + 1] - x[i]);
68 }
69
70 final PolynomialFunction[] polynomials = new PolynomialFunction[n];
71 final double[] coefficients = new double[2];
72 for (int i = 0; i < n; i++) {
73 coefficients[0] = y[i];
74 coefficients[1] = m[i];
75 polynomials[i] = new PolynomialFunction(coefficients);
76 }
77
78 return new PolynomialSplineFunction(x, polynomials);
79 }
80 }