view gnv-artifacts/src/main/java/de/intevation/gnv/math/LinearFunction.java @ 1119:7c4f81f74c47

merged gnv-artifacts
author Thomas Arendsen Hein <thomas@intevation.de>
date Fri, 28 Sep 2012 12:14:00 +0200
parents f953c9a559d8
children
line wrap: on
line source
/*
 * Copyright (c) 2010 by Intevation GmbH
 *
 * This program is free software under the LGPL (>=v2.1)
 * Read the file LGPL.txt coming with the software for details
 * or visit http://www.gnu.org/licenses/ if it does not exist.
 */

package de.intevation.gnv.math;

import org.apache.commons.math.FunctionEvaluationException;

import org.apache.commons.math.analysis.UnivariateRealFunction;

import org.apache.commons.math.optimization.fitting.ParametricRealFunction;

/**
 * Models a linear function to be usable in the fitting framework of
 * the Apache Commons Mathematics Library.
 *
 *  @author <a href="mailto:sascha.teichmann@intevation.de">Sascha L. Teichmann</a>
 */
public class LinearFunction
implements   ParametricRealFunction
{
    /**
     * Instance to prevent needless creations of instances.
     */
    public static final LinearFunction INSTANCE = new LinearFunction();

    /**
     * Specialized class to be useful in function evaluating
     * in the Apache Commons Mathematics Library.
     */
    public static class Univariate
    implements          UnivariateRealFunction
    {
        /**
         * The linear scaling factor.
         */
        protected double m;
        /**
         * The linear offset.
         */
        protected double b;

        /**
         * Default constructor.
         */
        public Univariate() {
        }

        /**
         * Constructor to create a Univariate with the linear parameters
         * of the line between (x1, y1) and (x2, y2).
         * @param x1 The x coordinate of the first point.
         * @param y1 The y coordinate of the first point.
         * @param x2 The x coordinate of the second point.
         * @param y2 The y coordinate of the second point.
         */
        public Univariate(double x1, double y1, double x2, double y2) {
            if (y1 == y2) {
                m = 0d;
                b = (x1 + x2)*0.5d;
            }
            else {
                m = (x1 - x2)/(y1 - y2);
                b = y1 - m*x1;
            }
        }

        public double value(double x) {
            return m*x + b;
        }
    } // class Univariate

    /**
     * Default constructor.
     */
    public LinearFunction() {
    }

    public double value(double x, double [] parameters)
    throws FunctionEvaluationException
    {
        return x*parameters[0] + parameters[1];
    }

    public double [] gradient(double x, double [] parameters)
    throws FunctionEvaluationException
    {
        return new double [] { x, 1f };
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org