Test if two numbers are equal within an absolute or relative tolerance whichever is larger. - Java java.lang

Java examples for java.lang:double

Description

Test if two numbers are equal within an absolute or relative tolerance whichever is larger.

Demo Code

/*/*from  w w  w . j  a  v  a 2s  .  co  m*/
 * Copyright (c) 2012 Diamond Light Source Ltd.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 */
//package com.java2s;

public class Main {
    /**
     * Test if two numbers are equal within an absolute or relative tolerance whichever is larger.
     * The relative tolerance is given by a percentage and calculated from the absolute maximum of the input numbers.
     * @param foo
     * @param bar
     * @param tolerance
     * @param percentage
     * @return true if foo equals bar within tolerance
     */
    public static boolean equalsWithinTolerances(Number foo, Number bar,
            Number tolerance, Number percentage) {
        final double a = foo.doubleValue();
        final double b = bar.doubleValue();
        final double t = tolerance.doubleValue();
        final double p = percentage.doubleValue();

        double r = p * Math.max(Math.abs(a), Math.abs(b)) / 100.; // relative tolerance
        if (r > t)
            return r >= Math.abs(a - b);
        return t >= Math.abs(a - b);
    }
}

Related Tutorials