001 /*
002 * Copyright 2011 Christian Kumpe http://kumpe.de/christian/java
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016 package de.kumpe.hadooptimizer.impl;
017
018 import java.util.Arrays;
019
020 import org.apache.commons.logging.Log;
021 import org.apache.commons.logging.LogFactory;
022
023 import de.kumpe.hadooptimizer.Evaluator;
024
025 /**
026 * A {@link Evaluator} for polynomials. It's created with the roots of the
027 * polynomial.
028 * <p>
029 * For the roots <i>x1, x2, x3,...</i> it evaluates the polynomial: <i>f(x) = (x
030 * - x1) * (x - x2) * (x - x3) * ...</i>
031 *
032 * @author <a href="http://kumpe.de/christian/java">Christian Kumpe</a>
033 */
034 public final class PolynomialEvaluator implements Evaluator<double[]> {
035 private static final long serialVersionUID = 1L;
036 private static final Log log = LogFactory.getLog(PolynomialEvaluator.class);
037
038 private final double[] roots;
039
040 public PolynomialEvaluator(final double... roots) {
041 if (0 != roots.length % 2) {
042 throw new IllegalArgumentException(
043 "PolynomialEvaluator needs an even number of roots.");
044 }
045 if (log.isDebugEnabled()) {
046 log.debug("Constructing new PolynomialEvaluator with the roots "
047 + Arrays.toString(roots));
048 }
049
050 this.roots = roots;
051 }
052
053 @Override
054 public double evaluate(final double[] individual) {
055 final double unboxedIndividual = individual[0];
056 double result = 1;
057 for (final double root : roots) {
058 result *= unboxedIndividual - root;
059 }
060 return result;
061 }
062
063 @Override
064 public String toString() {
065 return "PolynomialEvaluator [roots=" + Arrays.toString(roots) + "]";
066 }
067 }