1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.nabla;
18  
19  import java.util.Random;
20  
21  public class Polynomial implements ReferenceFunction {
22  
23      /** Build a random polynomial.
24       * @param random random generator to use
25       * @param degree
26       * @return a random polynomial
27       */
28      public static Polynomial randomPolynomial(Random random, int degree) {
29          double[] coeffs = new double[degree+1];
30          for (int i = 0; i < coeffs.length; ++i) {
31              coeffs[i] = random.nextDouble();
32          }
33          return new Polynomial(coeffs);
34      }
35  
36      /** Build a polynomial from its coefficients.
37       * @param coeffs coefficients array in <em>decreasing degree</em> order
38       */
39      public Polynomial(double[] coeffs) {
40          this.coeffs = coeffs;
41      }
42  
43      public void addToSelf(Polynomial other) {
44          double[] newCoeffs = new double[Math.max(coeffs.length, other.coeffs.length)];
45          System.arraycopy(coeffs, 0, newCoeffs, 0, coeffs.length);
46          for (int i = 0; i < other.coeffs.length; ++i) {
47              newCoeffs[i] += other.coeffs[i];
48          }
49          coeffs = newCoeffs;
50      }
51  
52      public double f(double t) {
53          double y = 0;
54          for (int i = 0; i < coeffs.length; ++i) {
55              y = y * t + coeffs[i];
56          }
57          return y;
58      }
59  
60      public double fPrime(double t) {
61          double d = 0;
62          for (int i = 0; i < coeffs.length - 1; ++i) {
63              d = d * t + (coeffs.length - 1 - i) * coeffs[i];
64          }
65          return d;
66      }
67  
68      private double[] coeffs;
69  
70  }