Java Number Compare compareDoublesWithTolerance(double aa, double bb, double tolerance)

Here you can find the source of compareDoublesWithTolerance(double aa, double bb, double tolerance)

Description

compare Doubles With Tolerance

License

Open Source License

Declaration

public static boolean compareDoublesWithTolerance(double aa, double bb, double tolerance) 

Method Source Code

//package com.java2s;
/*//from   w w  w. j av a2  s. c o m
 * Copyright (C) 2007 Alberto Duina, SPEDALI CIVILI DI BRESCIA, Brescia ITALY
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

import java.math.BigDecimal;

public class Main {
    public static boolean compareDoublesWithTolerance(double aa, double bb, double tolerance) {
        if (Double.compare(aa, bb) == 0)
            return true;
        return Math.abs(aa - bb) < tolerance;
    }

    public static boolean compareDoublesWithTolerance(double aa, double bb, int digits) {

        // IJ.log ("aa= "+aa+" bb="+bb+" digits=" +digits);

        double uno = roundDoubleDecimals(aa, digits);
        double due = roundDoubleDecimals(bb, digits);
        double tre = Math.abs(roundDoubleDecimals(aa, digits) - roundDoubleDecimals(bb, digits));
        // IJ.log ("uno= "+uno+" due="+due+" tre=" +tre);
        // MyLog.waitHere();

        return tre == 0;
    }

    public static double roundDoubleDecimals(double x1, int decimalPlaces) {
        BigDecimal bd = new BigDecimal(x1);
        bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_DOWN);
        return bd.doubleValue();
    }
}

Related

  1. compare(final Number x, final Number y)
  2. compare(Object o1, Object o2)
  3. compareDoubleAgainstLong(double lhs, long rhs)
  4. compareStringsAsNumbers(String s1, String s2, String op)
  5. compareTo(double v1, double v2)
  6. compareTo(Object val1, Object val2)
  7. compareTo(Object value1, Object value2)