sascha@655: package de.intevation.flys.artifacts.math;
sascha@655: 
sascha@742: public final class Linear
sascha@655: implements         Function
sascha@655: {
sascha@655:     private double m;
sascha@655:     private double b;
sascha@655: 
sascha@655:     public Linear(
sascha@655:         double x1, double x2,
sascha@655:         double y1, double y2
sascha@655:     ) {
sascha@655:         // y1 = m*x1 + b
sascha@655:         // y2 = m*x2 + b
sascha@655:         // y2 - y1 = m*(x2 - x1)
sascha@655:         // m = (y2 - y1)/(x2 - x1) # x2 != x1
sascha@655:         // b = y1 - m*x1
sascha@655: 
sascha@655:         if (x1 == x2) {
sascha@655:             m = 0;
sascha@655:             b = 0.5*(y1 + y2);
sascha@655:         }
sascha@655:         else {
sascha@655:             m = (y2 - y1)/(x2 - x1);
sascha@655:             b = y1 - m*x1;
sascha@655:         }
sascha@655:     }
sascha@655: 
sascha@655:     public static final double linear(
sascha@655:         double x,
sascha@655:         double x1, double x2,
sascha@655:         double y1, double y2
sascha@655:     ) {
sascha@655:         // y1 = m*x1 + b
sascha@655:         // y2 = m*x2 + b
sascha@655:         // y2 - y1 = m*(x2 - x1)
sascha@655:         // m = (y2 - y1)/(x2 - x1) # x2 != x1
sascha@655:         // b = y1 - m*x1
sascha@655: 
sascha@655:         if (x1 == x2) {
sascha@655:             return 0.5*(y1 + y2);
sascha@655:         }
sascha@655:         double m = (y2 - y1)/(x2 - x1);
sascha@655:         double b = y1 - m*x1;
sascha@655:         return x*m + b;
sascha@655:     }
sascha@655: 
sascha@655:     @Override
sascha@655:     public double value(double x) {
sascha@655:         return m*x + b;
sascha@655:     }
sascha@655: 
sascha@655:     public static final double factor(double x, double p1, double p2) {
sascha@655:         // 0 = m*p1 + b <=> b = -m*p1
sascha@655:         // 1 = m*p2 + b
sascha@655:         // 1 = m*(p2 - p1)
sascha@655:         // m = 1/(p2 - p1) # p1 != p2
sascha@655:         // f(x) = x/(p2-p1) - p1/(p2-p1) <=> (x-p1)/(p2-p1)
sascha@655: 
sascha@655:         return p1 == p2 ? 0.0 : (x-p1)/(p2-p1);
sascha@655:     }
sascha@655: 
sascha@655:     public static final double weight(double factor, double a, double b) {
sascha@655:         //return (1.0-factor)*a + factor*b;
sascha@655:         return a + factor*(b-a);
sascha@655:     }
sascha@3736: 
sascha@3736:     public static final void weight(
sascha@3736:         double factor,
sascha@3736:         double [] a, double [] b, double [] c
sascha@3736:     ) {
sascha@3736:         int N = Math.min(Math.min(a.length, b.length), c.length);
sascha@3736:         for (int i = 0; i < N; ++i) {
sascha@3736:             c[i] = weight(factor, a[i], b[i]);
sascha@3736:         }
sascha@3736:     }
sascha@655: }
sascha@655: // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :