Here you can find the source of compareDoublesWithTolerance(double aa, double bb, double tolerance)
public static boolean compareDoublesWithTolerance(double aa, double bb, double tolerance)
//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(); } }