1 16 package org.apache.commons.math.analysis; 17 18 43 public class SplineInterpolator implements UnivariateRealInterpolator { 44 45 51 public UnivariateRealFunction interpolate(double x[], double y[]) { 52 if (x.length != y.length) { 53 throw new IllegalArgumentException ("Dataset arrays must have same length."); 54 } 55 56 if (x.length < 3) { 57 throw new IllegalArgumentException 58 ("At least 3 datapoints are required to compute a spline interpolant"); 59 } 60 61 int n = x.length - 1; 63 64 for (int i = 0; i < n; i++) { 65 if (x[i] >= x[i + 1]) { 66 throw new IllegalArgumentException ("Dataset x values must be strictly increasing."); 67 } 68 } 69 70 double h[] = new double[n]; 72 for (int i = 0; i < n; i++) { 73 h[i] = x[i + 1] - x[i]; 74 } 75 76 double mu[] = new double[n]; 77 double z[] = new double[n + 1]; 78 mu[0] = 0d; 79 z[0] = 0d; 80 double g = 0; 81 for (int i = 1; i < n; i++) { 82 g = 2d * (x[i+1] - x[i - 1]) - h[i - 1] * mu[i -1]; 83 mu[i] = h[i] / g; 84 z[i] = (3d * (y[i + 1] * h[i - 1] - y[i] * (x[i + 1] - x[i - 1])+ y[i - 1] * h[i]) / 85 (h[i - 1] * h[i]) - h[i - 1] * z[i - 1]) / g; 86 } 87 88 double b[] = new double[n]; 90 double c[] = new double[n + 1]; 91 double d[] = new double[n]; 92 93 z[n] = 0d; 94 c[n] = 0d; 95 96 for (int j = n -1; j >=0; j--) { 97 c[j] = z[j] - mu[j] * c[j + 1]; 98 b[j] = (y[j + 1] - y[j]) / h[j] - h[j] * (c[j + 1] + 2d * c[j]) / 3d; 99 d[j] = (c[j + 1] - c[j]) / (3d * h[j]); 100 } 101 102 PolynomialFunction polynomials[] = new PolynomialFunction[n]; 103 double coefficients[] = new double[4]; 104 for (int i = 0; i < n; i++) { 105 coefficients[0] = y[i]; 106 coefficients[1] = b[i]; 107 coefficients[2] = c[i]; 108 coefficients[3] = d[i]; 109 polynomials[i] = new PolynomialFunction(coefficients); 110 } 111 112 return new PolynomialSplineFunction(x, polynomials); 113 } 114 115 } 116 | Popular Tags |