1 16 package org.apache.commons.math.analysis; 17 18 import java.io.Serializable ; 19 import java.util.Arrays ; 20 21 import org.apache.commons.math.FunctionEvaluationException; 22 23 55 public class PolynomialSplineFunction implements UnivariateRealFunction, Serializable { 56 57 58 static final long serialVersionUID = 7011031166416885789L; 59 60 61 private double knots[]; 62 63 70 private PolynomialFunction polynomials[] = null; 71 72 76 private int n = 0; 77 78 79 94 public PolynomialSplineFunction(double knots[], PolynomialFunction polynomials[]) { 95 if (knots.length < 2) { 96 throw new IllegalArgumentException 97 ("Not enough knot values -- spline partition must have at least 2 points."); 98 } 99 if (knots.length - 1 != polynomials.length) { 100 throw new IllegalArgumentException 101 ("Number of polynomial interpolants must match the number of segments."); 102 } 103 if (!isStrictlyIncreasing(knots)) { 104 throw new IllegalArgumentException 105 ("Knot values must be strictly increasing."); 106 } 107 108 this.n = knots.length -1; 109 this.knots = new double[n + 1]; 110 System.arraycopy(knots, 0, this.knots, 0, n + 1); 111 this.polynomials = new PolynomialFunction[n]; 112 System.arraycopy(polynomials, 0, this.polynomials, 0, n); 113 } 114 115 130 public double value(double v) throws FunctionEvaluationException { 131 if (v < knots[0] || v > knots[n]) { 132 throw new FunctionEvaluationException(v,"Argument outside domain"); 133 } 134 int i = Arrays.binarySearch(knots, v); 135 if (i < 0) { 136 i = -i - 2; 137 } 138 if ( i >= polynomials.length ) { 142 i--; 143 } 144 return polynomials[i].value(v - knots[i]); 145 } 146 147 151 public UnivariateRealFunction derivative() { 152 return polynomialSplineDerivative(); 153 } 154 155 160 public PolynomialSplineFunction polynomialSplineDerivative() { 161 PolynomialFunction derivativePolynomials[] = new PolynomialFunction[n]; 162 for (int i = 0; i < n; i++) { 163 derivativePolynomials[i] = polynomials[i].polynomialDerivative(); 164 } 165 return new PolynomialSplineFunction(knots, derivativePolynomials); 166 } 167 168 174 public int getN() { 175 return n; 176 } 177 178 186 public PolynomialFunction[] getPolynomials() { 187 PolynomialFunction p[] = new PolynomialFunction[n]; 188 System.arraycopy(polynomials, 0, p, 0, n); 189 return p; 190 } 191 192 200 public double[] getKnots() { 201 double out[] = new double[n + 1]; 202 System.arraycopy(knots, 0, out, 0, n + 1); 203 return out; 204 } 205 206 214 private static boolean isStrictlyIncreasing(double[] x) { 215 for (int i = 1; i < x.length; ++i) { 216 if (x[i - 1] >= x[i]) { 217 return false; 218 } 219 } 220 return true; 221 } 222 } 223 | Popular Tags |