1 /*
2 * Copyright (C) 2016 Alberto Irurueta Carro (alberto@irurueta.com)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package com.irurueta.numerical;
17
18 import com.irurueta.algebra.Complex;
19
20 /**
21 * Utility class to evaluate polynomials having either real or complex
22 * coefficients.
23 */
24 public class PolynomialEvaluator {
25
26 /**
27 * Empty constructor.
28 */
29 protected PolynomialEvaluator() {
30 }
31
32 /**
33 * Evaluates polynomial formed by provided polynomial parameters at provided
34 * point x. The polynomial of degree n is defined as:
35 * p(x) = a0 * x^n + a1 * x^(n - 1) + ... a(n-1) * x + an
36 * hence, the array of parameters is [a0, a1, ... a(n-1), an].
37 *
38 * @param polyParams array of polynomial parameters.
39 * @param x point where polynomial is evaluated.
40 * @return result of evaluation.
41 * @throws IllegalArgumentException if provided array is null or has length
42 * 0.
43 */
44 public static double evaluate(final double[] polyParams, final double x) {
45 if (polyParams == null || polyParams.length == 0) {
46 throw new IllegalArgumentException();
47 }
48
49 final var length = polyParams.length;
50
51 var result = 0.0;
52 var powX = 1.0;
53 for (var i = length - 1; i >= 0; i--) {
54 result += polyParams[i] * powX;
55 powX *= x;
56 }
57
58 return result;
59 }
60
61 /**
62 * Evaluates polynomial formed by provided polynomial parameters at provided
63 * point x. The polynomial of degree n is defined as:
64 * p(x) = a0 * x^n + a1 * x^(n - 1) + ... a(n-1) * x + an
65 * hence, the array of parameters is [a0, a1, ... a(n-1), an].
66 *
67 * @param polyParams array of polynomial parameters.
68 * @param x point where polynomial is evaluated.
69 * @return result of evaluation.
70 * @throws IllegalArgumentException if provided array is null or has length
71 * 0.
72 */
73 public static Complex evaluate(final Complex[] polyParams, final Complex x) {
74 if (polyParams == null || polyParams.length == 0) {
75 throw new IllegalArgumentException();
76 }
77
78 final var length = polyParams.length;
79
80 final var result = new Complex();
81 final var powX = new Complex(1.0, 0.0);
82 final var tmp = new Complex();
83 for (var i = length - 1; i >= 0; i--) {
84
85 polyParams[i].multiply(powX, tmp);
86 result.add(tmp);
87
88 powX.multiply(x);
89 }
90
91 return result;
92 }
93 }