Java Double Number Almost Equal almostEqual(double a, double b)

Here you can find the source of almostEqual(double a, double b)

Description

almost Equal

License

Open Source License

Declaration

public static boolean almostEqual(double a, double b) 

Method Source Code

//package com.java2s;
/**/*  w  w w .  j  av a2s  . c  o m*/
 * Copyright 2015 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    private static final double ABSOLUTE_EPSILON = 1e-7;
    private static final double RELATIVE_EPSILON = 1e-10;

    public static boolean almostEqual(double a, double b) {
        if (Math.abs(a - b) <= ABSOLUTE_EPSILON)
            return true;

        double a1 = a * (1 - RELATIVE_EPSILON);
        double a2 = a * (1 + RELATIVE_EPSILON);
        if ((a1 <= b) && (b <= a2))
            return true;
        if ((a2 <= b) && (b <= a1))
            return true;

        double b1 = b * (1 - RELATIVE_EPSILON);
        double b2 = b * (1 + RELATIVE_EPSILON);
        if ((b1 <= a) && (a <= b2))
            return true;
        if ((b2 <= a) && (a <= b1))
            return true;

        return false;
    }
}

Related

  1. almost(double a, double b, double prec)
  2. almostEqual(double a, double b, double delta)
  3. almostEqual(double[][] a, double[][] b, double delta)
  4. almostEqual(final double aDouble, final double otherDouble)
  5. almostEquals(double d1, double d2)