diff gnv-artifacts/src/main/java/de/intevation/gnv/math/LinearFunction.java @ 875:5e9efdda6894

merged gnv-artifacts/1.0
author Thomas Arendsen Hein <thomas@intevation.de>
date Fri, 28 Sep 2012 12:13:56 +0200 (2012-09-28)
parents a645bd23c1c8
children f953c9a559d8
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/gnv-artifacts/src/main/java/de/intevation/gnv/math/LinearFunction.java	Fri Sep 28 12:13:56 2012 +0200
@@ -0,0 +1,87 @@
+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