Example usage for org.apache.commons.math3.util FastMath abs

List of usage examples for org.apache.commons.math3.util FastMath abs

Introduction

In this page you can find the example usage for org.apache.commons.math3.util FastMath abs.

Prototype

public static double abs(double x) 

Source Link

Document

Absolute value.

Usage

From source file:fuzzy.mf.GeneralizedBellShapedMembershipFunction.java

public Double evaluate(Double x) {
    return 1 / (1 + FastMath.pow(FastMath.abs((x - c) / a), 2 * b));
}

From source file:lirmm.inria.fr.evaluation.Metrics.java

public static void evaluate(DataMatrix R, BigSparseRealMatrix U, BigSparseRealMatrix V) {
    OpenLongToDoubleHashMap rowsMAE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap rowsRMSE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap rowsT = new OpenLongToDoubleHashMap(0.0);
    //-------------------------------------------------------------------
    OpenLongToDoubleHashMap columnsMAE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap columnsRMSE = new OpenLongToDoubleHashMap(0.0);
    OpenLongToDoubleHashMap columnsT = new OpenLongToDoubleHashMap(0.0);

    double RMSE = 0;
    double MAE = 0;
    double RMSERand = 0;
    double MAERand = 0;
    int k = 0;//from www .j  a v a2s  .c  o m
    for (OpenLongToDoubleHashMap.Iterator iterator = R.getTestSetEntries().iterator(); iterator.hasNext();) {
        k++;
        iterator.advance();
        final double value = iterator.value();
        final long key = iterator.key();
        final int i, j;
        i = (int) (key / R.getColumnDimension());
        j = (int) (key % R.getColumnDimension());
        //            double estimation = U.transpose().getRowVector(j).dotProduct(V.getColumnVector(j));
        double estimation = getDotProduct(U, i, V, j);
        RMSE += FastMath.pow(value - estimation, 2);
        MAE += FastMath.abs(value - estimation);
        double r = Math.random() * R.getMax();
        RMSERand += FastMath.pow(value - r, 2);
        MAERand += FastMath.abs(value - r);

        double v = rowsMAE.get(R.getRowNonZeroEntry(i));
        rowsMAE.put(R.getRowNonZeroEntry(i), v + FastMath.abs(value - estimation));
        v = rowsRMSE.get(R.getRowNonZeroEntry(i));
        rowsRMSE.put(R.getRowNonZeroEntry(i), v + FastMath.pow(value - estimation, 2));
        v = rowsT.get(R.getRowNonZeroEntry(i));
        rowsT.put(R.getRowNonZeroEntry(i), v + 1);

        v = columnsMAE.get(R.getColumnNonZeroEntry(j));
        columnsMAE.put(R.getColumnNonZeroEntry(j), v + FastMath.abs(value - estimation));
        v = columnsRMSE.get(R.getColumnNonZeroEntry(j));
        columnsRMSE.put(R.getColumnNonZeroEntry(j), v + FastMath.pow(value - estimation, 2));
        v = columnsT.get(R.getColumnNonZeroEntry(j));
        columnsT.put(R.getColumnNonZeroEntry(j), v + 1);
    }
    System.out.println("******************************************");
    for (OpenLongToDoubleHashMap.Iterator iterator = rowsMAE.iterator(); iterator.hasNext();) {
        iterator.advance();
        final long key = iterator.key();
        double localMAE = rowsMAE.get(key) / rowsT.get(key);
        double localRMSE = FastMath.sqrt(rowsRMSE.get(key) / rowsT.get(key));
        System.out.println(key + "\t" + (int) rowsT.get(key) + "\t" + localMAE + "\t" + localRMSE);
    }
    System.out.println("******************************************");
    for (OpenLongToDoubleHashMap.Iterator iterator = columnsMAE.iterator(); iterator.hasNext();) {
        iterator.advance();
        final long key = iterator.key();
        double localMAE = columnsMAE.get(key) / columnsT.get(key);
        double localRMSE = FastMath.sqrt(columnsRMSE.get(key) / columnsT.get(key));
        System.out.println(key + "\t" + (int) columnsT.get(key) + "\t" + localMAE + "\t" + localRMSE);
    }
    RMSE /= k;
    MAE /= k;
    RMSE = FastMath.sqrt(RMSE);
    RMSERand /= k;
    MAERand /= k;
    RMSERand = FastMath.sqrt(RMSERand);
    System.out.println("******************************************");
    System.out.println("Type\tMAE\tRMSE");
    System.out.println("DPMF\t" + MAE + "\t" + RMSE);
    System.out.println("Random\t" + MAERand + "\t" + RMSERand);
    System.out.println("******************************************");
}

From source file:com.clust4j.metrics.pairwise.MinkowskiDistance.java

@Override
public double getPartialDistance(final double[] a, final double[] b) {
    VecUtils.checkDims(a, b);//from w ww. j  a  va  2 s  .c  o m

    double sum = 0;
    for (int i = 0; i < a.length; i++) {
        // Don't use math.abs -- too expensive
        double diff = a[i] - b[i];
        sum += FastMath.pow(FastMath.abs(diff), p);
    }

    return sum;
}

From source file:com.cloudera.oryx.rdf.common.eval.Evaluation.java

/**
 * @param testSet test set to evaluate on
 * @return average absolute value of numeric target value in the test set
 */// ww  w . j a v a2s  .c  o m
private static double meanAbs(Iterable<Example> testSet) {
    StorelessUnivariateStatistic mean = new Mean();
    for (Example test : testSet) {
        NumericFeature actual = (NumericFeature) test.getTarget();
        mean.increment(FastMath.abs(actual.getValue()));
    }
    return mean.getResult();
}

From source file:net.sf.dsp4j.octave_3_2_4.m.polynomial.Roots.java

public static Complex[] roots(RealVector v) {

    if (v.isInfinite() || v.isNaN()) {
        throw new RuntimeException("roots: inputs must not contain Inf or NaN");
    }//from  w  w w. ja  va  2 s  .  c  om

    int n = v.getDimension();

    // ## If v = [ 0 ... 0 v(k+1) ... v(k+l) 0 ... 0 ], we can remove the
    // ## leading k zeros and n - k - l roots of the polynomial are zero.

    int[] f = new int[v.getDimension()];
    if (v.getDimension() > 0) {
        int fI = 0;
        double max = v.getMaxValue();
        double min = FastMath.abs(v.getMinValue());
        if (min > max) {
            max = min;
        }
        RealVector v1 = v.mapDivide(max);
        f = OctaveBuildIn.find(v1);
    }

    Complex[] r = new Complex[0];
    if (f.length > 0 && n > 1) {
        v = v.getSubVector(f[0], f[f.length - 1] - f[0] + 1);
        if (v.getDimension() > 1) {
            double[] ones = new double[v.getDimension() - 2];
            Arrays.fill(ones, 1);
            RealMatrix A = OctaveBuildIn.diag(ones, -1);
            for (int i = 0; i < A.getRowDimension(); i++) {
                A.setEntry(i, 0, -v.getEntry(i + 1) / v.getEntry(0));
            }
            try {
                r = Eig.eig(A);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (f[f.length - 1] < n) {
                int diffLength = n - 1 - f[f.length - 1];
                if (diffLength > 0) {
                    int rl = r.length;
                    r = Arrays.copyOf(r, r.length + diffLength);
                    Arrays.fill(r, rl, r.length, Complex.ZERO);
                }
            }
        } else {
            r = new Complex[n - f[f.length - 1]];
            Arrays.fill(r, Complex.ZERO);
        }
    } else {
        r = new Complex[0];
    }
    return r;

}

From source file:gamlss.algorithm.GlimFitCG.java

public ArrayRealVector glimFitFunctionCG(GAMLSSFamilyDistribution distr, ArrayRealVector response,
        Hashtable<Integer, BlockRealMatrix> X, ArrayRealVector fv, ArrayRealVector weights,
        int whichDistParameter, double step, double offSet, double globalDeviance,
        Hashtable<String, ArrayRealVector> cgData, MakeLinkFunction makelink) {

    int itn = 0;//from w w w. j a v  a2 s .  c  o  m
    double[] temp = new double[0];

    //G.dev.in <- G.dev+1
    //     double gDevIn = globalDeviance +1;

    //i.G.dev <- G.dev
    double gDev = globalDeviance;

    double gDevOld = globalDeviance + 1;

    //first.iter <- FALSE  
    boolean firstIter = false;

    //while ( abs(G.dev.in -i.G.dev) > i.c.crit && i.iter < i.n.cyc )
    while (FastMath.abs(gDevOld - gDev) > Controls.GLIM_CONV_CRIT && itn < Controls.GLIM_NUM_CYCLES) {

        //i.iter <- i.iter+1
        itn = itn + 1;

        //for (int i = 1; i < distr.getNumberOfDistribtionParameters()+1; i++ ){
        switch (whichDistParameter) {
        case DistributionSettings.MU:
            // whichDistParameter = DistributionSettings.MU;

            //adj.mu <- -(w.mu.sigma*(eta.sigma-eta.old.sigma)+w.mu.nu*(eta.nu-eta.old.nu)+w.mu.tau*(eta.tau-eta.old.tau))/w.mu 
            adj = setAdj(cgData.get("wMuSigma"), cgData.get("eta" + DistributionSettings.SIGMA),
                    cgData.get("etaOld" + DistributionSettings.SIGMA), cgData.get("wMuNu"),
                    cgData.get("eta" + DistributionSettings.NU), cgData.get("etaOld" + DistributionSettings.NU),
                    cgData.get("wMuTau"), cgData.get("eta" + DistributionSettings.TAU),
                    cgData.get("etaOld" + DistributionSettings.TAU), cgData.get("w" + DistributionSettings.MU));

            cgData.put("adj" + DistributionSettings.MU, adj);

            break;
        case DistributionSettings.SIGMA:
            // whichDistParameter = DistributionSettings.SIGMA;

            // adj.sigma <- -(w.mu.sigma*(eta.mu-eta.old.mu)+ w.sigma.nu*(eta.nu-eta.old.nu)+w.sigma.tau*(eta.tau-eta.old.tau))/w.sigma 
            adj = setAdj(cgData.get("wMuSigma"), cgData.get("eta" + DistributionSettings.MU),
                    cgData.get("etaOld" + DistributionSettings.MU), cgData.get("wSigmaNu"),
                    cgData.get("eta" + DistributionSettings.NU), cgData.get("etaOld" + DistributionSettings.NU),
                    cgData.get("wSigmaTau"), cgData.get("eta" + DistributionSettings.TAU),
                    cgData.get("etaOld" + DistributionSettings.TAU),
                    cgData.get("w" + DistributionSettings.SIGMA));

            cgData.put("adj" + DistributionSettings.SIGMA, adj);

            break;
        case DistributionSettings.NU:
            // whichDistParameter = DistributionSettings.NU;
            break;
        case DistributionSettings.TAU:
            // whichDistParameter = DistributionSettings.TAU;
            break;
        }

        //wv.mu  <- z.mu+adj.mu
        ArrayRealVector wv = setWV(cgData.get("z" + whichDistParameter),
                cgData.get("adj" + whichDistParameter));

        //mu.fit <<- lm.wfit(x=mu.X,y=wv.mu,w=w.mu*w,method="qr") 
        wls.newSampleData(wv, X.get(whichDistParameter).copy(),
                cgData.get("w" + whichDistParameter).ebeMultiply(weights));
        ArrayRealVector fit = (ArrayRealVector) wls.calculateFittedValues(false);

        //System.out.println(wls.calculateBeta());
        //           bettas.put(whichDistParameter, (ArrayRealVector) wls.calculateBeta());

        //mu.fit$eta <<- eta.mu <- mu.fit$fitted.values+mu.offset
        temp = new double[fit.getDimension()];
        for (int j = 0; j < temp.length; j++) {
            temp[j] = fit.getEntry(j) + offSet;
        }
        //eta = new ArrayRealVector(temp,false);
        cgData.put("eta" + whichDistParameter, new ArrayRealVector(temp, false));
        temp = null;

        //mu.fit$fv <<-    mu <<- mu.object$linkinv(eta.mu)

        ArrayRealVector dParam = makelink.linkInv(distr.getDistributionParameterLink(whichDistParameter),
                cgData.get("eta" + whichDistParameter));

        distr.setDistributionParameter(whichDistParameter, dParam);

        //mu.fit$wv <<- wv.mu
        //mu.fit$wt <<- w.mu  

        //G.dev.in <- i.G.dev
        gDevOld = gDev;

        //G.dev.incr <- eval(G.dev.expr) 
        //i.G.dev <- sum(w*G.dev.incr)
        gDev = weights.dotProduct(distr.globalDevianceIncreament(response));

        if (gDev > gDevOld && itn >= 2 && Controls.AUTO_STEP) {
            for (int i = 0; i < 5; i++) {

                //eta.mu <- (eta.mu+eta.old.mu)/2
                ArrayRealVector etaM = etaMean(cgData.get("eta" + whichDistParameter),
                        cgData.get("etaOld" + whichDistParameter));
                cgData.put("eta" + whichDistParameter, etaM);
                //mu <<- mu.object$linkinv(eta.mu) 

                distr.setDistributionParameter(whichDistParameter,
                        makelink.linkInv(distr.getDistributionParameterLink(whichDistParameter), etaM));

                //if(length(who.mu) > 0) s.mu <- (s.mu+s.mu.old)/2 
                //   }
            }
        }

        //if(i.trace)
        if (Controls.GLIM_TRACE) {
            //cat("CG inner iteration ", iter, ": Global Deviance = ",format(round(i.G.dev, 4)), " \n", sep = "")           
            System.err.println("CG inner iteration " + itn + " : Global Deviance = " + gDev);
        }
        //if (i.G.dev > (G.dev.in+gd.tol) && iter >1 )
        if (gDev > (gDevOld + Controls.GLOB_DEVIANCE_TOL) && itn > 1) {

            //stop(paste("The global deviance is increasing in the inner CG loop", "\n","Try different steps for the parameters or the model maybe inappropriate"))
            System.out.println(
                    "The global deviance is increasing in the inner CG loop, try different steps for the parameters or the model maybe inappropriate");
            break;
        }
    }

    //G.dev.old <- G.dev
    //        gDevOld = gDev;

    //G.dev.incr <- eval(G.dev.expr)   
    //G.dev <- sum(w*G.dev.incr)
    //     gDev = weights.dotProduct(distr.globalDevianceIncreament(response));

    //if (G.dev > G.dev.old && iter >= 2 && autostep == TRUE)

    return (ArrayRealVector) wls.calculateBeta();
}

From source file:net.nicoulaj.benchmarks.math.DoubleAbs.java

@GenerateMicroBenchmark
public void commonsmath(BlackHole hole) {
    for (int i = 0; i < data.length - 1; i++)
        hole.consume(FastMath.abs(data[i]));
}

From source file:com.clust4j.kernel.GeneralizedMinKernel.java

@Override
public double getSimilarity(final double[] a, final double[] b) {
    VecUtils.checkDims(a, b);/*from  w ww  .j a v  a  2 s .  c  om*/

    double sum = 0;
    for (int i = 0; i < a.length; i++)
        sum += FastMath.min(FastMath.pow(FastMath.abs(a[i]), getAlpha()),
                FastMath.pow(FastMath.abs(b[i]), getBeta()));

    return sum;
}

From source file:com.clust4j.optimize.BrentDownhillOptimizer.java

private void doCoreAlgorithm() {
    double xa = bracket.xa;
    double xb = bracket.xb;
    double xc = bracket.xc;

    /*/* www.j  a v a 2 s  . c om*/
    double fa = bracket.fa;
    double fb = bracket.fb;
    double fc = bracket.fc;
    */

    funcalls = bracket.funcalls;

    // begin core algo
    double x, w, v, fw, fv, fx, a, b;
    x = w = v = xb; // init all to xb
    fw = fv = fx = this.optimizer.doCall(x); // init all do f(x)

    if (xa < xc) {
        a = xa;
        b = xc;
    } else {
        a = xc;
        b = xa;
    }

    double deltAX = 0.0;
    funcalls = 1;
    iter = 0;

    double tol1, tol2, xmid, rat = 0.0, tmp1, tmp2, p, dxtmp, u, fu;
    while (iter < maxIter) {
        tol1 = tol * FastMath.abs(x) + mintol;
        tol2 = 2.0 * tol1;
        xmid = 0.5 * (a + b);

        // check for convergence
        if (FastMath.abs(x - xmid) < (tol2 - 0.5 * (b - a)))
            break;

        /*
         * rat is only set in the true case of this. the first iteration
         * should always be true, though, so initializing rat to 0.0 shouldn't
         * cause any issues later...
         */
        if (FastMath.abs(deltAX) <= tol1) { // golden section step
            if (x >= xmid) {
                deltAX = a - x;
            } else {
                deltAX = b - x;
            }

            rat = cg * deltAX;
        } else { // parabolic step
            tmp1 = (x - w) * (fx - fv);
            tmp2 = (x - v) * (fx - fw);
            p = (x - v) * tmp2 - (x - w) * tmp1;
            tmp2 = 2.0 * (tmp2 - tmp1);
            if (tmp2 > 0.0) {
                p = -p;
            }

            tmp2 = FastMath.abs(tmp2);
            dxtmp = deltAX;
            deltAX = rat;

            // check parabolic fit:
            if ((p > tmp2 * (a - x)) && (p < tmp2 * (b - x))
                    && (FastMath.abs(p) < FastMath.abs(0.5 * tmp2 * dxtmp))) {
                rat = p * 1.0 / tmp2;
                u = x + rat;

                if ((u - a) < tol2 || (b - u) < tol2) {
                    if (xmid - x >= 0) {
                        rat = tol1;
                    } else {
                        rat = -tol1;
                    }
                }
            } else {
                if (x >= xmid) {
                    deltAX = a - x;
                } else {
                    deltAX = b - x;
                }

                rat = cg * deltAX;
            }
        }

        // update by at least tol1
        if (FastMath.abs(rat) < tol1) {
            if (rat >= 0) {
                u = x + tol1;
            } else {
                u = x - tol1;
            }
        } else {
            u = x + rat;
        }

        fu = this.optimizer.doCall(u);
        funcalls++;

        // update values
        if (fu > fx) {
            if (u < x) {
                a = u;
            } else {
                b = u;
            }

            if (fu <= fw || w == x) {
                v = w;
                w = u;
                fv = fw;
                fw = fu;
            } else if ((fu <= fv) || (v == x) || (v == w)) {
                v = u;
                fv = fu;
            }
        } else {
            if (u >= x) {
                a = x;
            } else {
                b = x;
            }

            v = w;
            w = x;
            x = u;
            fv = fw;
            fw = fx;
            fx = fu;
        }

        iter++;
    }

    // end core algorithm
    this.xmin = x;
    this.fval = fx;
    return;
}

From source file:com.clust4j.algo.preprocess.YeoJohnsonTransformer.java

private static boolean nearZero(double a) {
    return FastMath.abs(a) <= zero;
}