1 16 package org.apache.commons.math.analysis; 17 18 import java.io.Serializable ; 19 20 28 public class PolynomialFunction implements DifferentiableUnivariateRealFunction, Serializable { 29 30 31 static final long serialVersionUID = 3322454535052136809L; 32 33 38 private double coefficients[]; 39 40 53 public PolynomialFunction(double c[]) { 54 super(); 55 if (c.length < 1) { 56 throw new IllegalArgumentException ("Polynomial coefficient array must have postive length."); 57 } 58 this.coefficients = new double[c.length]; 59 System.arraycopy(c, 0, this.coefficients, 0, c.length); 60 } 61 62 72 public double value(double x) { 73 return evaluate(coefficients, x); 74 } 75 76 77 82 public int degree() { 83 return coefficients.length - 1; 84 } 85 86 94 public double[] getCoefficients() { 95 double[] out = new double[coefficients.length]; 96 System.arraycopy(coefficients,0, out, 0, coefficients.length); 97 return out; 98 } 99 100 110 protected static double evaluate(double[] coefficients, double argument) { 111 int n = coefficients.length; 112 if (n < 1) { 113 throw new IllegalArgumentException ("Coefficient array must have positive length for evaluation"); 114 } 115 double result = coefficients[n - 1]; 116 for (int j = n -2; j >=0; j--) { 117 result = argument * result + coefficients[j]; 118 } 119 return result; 120 } 121 122 130 protected static double[] differentiate(double[] coefficients) { 131 int n = coefficients.length; 132 if (n < 1) { 133 throw new IllegalArgumentException ("Coefficient array must have positive length for differentiation"); 134 } 135 if (n == 1) { 136 return new double[]{0}; 137 } 138 double[] result = new double[n - 1]; 139 for (int i = n - 1; i > 0; i--) { 140 result[i - 1] = (double) i * coefficients[i]; 141 } 142 return result; 143 } 144 145 150 public PolynomialFunction polynomialDerivative() { 151 return new PolynomialFunction(differentiate(coefficients)); 152 } 153 154 159 public UnivariateRealFunction derivative() { 160 return polynomialDerivative(); 161 } 162 163 } 164 | Popular Tags |