/** * Check if two numbers are nearly equal with given absolute tolerance. * * @param a first number. * @param b second number. * @param maxAbsDiff the maximum {@link #absoluteDifference absolute difference} the two numbers may have. * @return true if within tolerance. */ public static boolean nearlyEqualsAbs(float a, float b, float maxAbsDiff) { return absoluteDifference(a, b) <= Math.abs(maxAbsDiff); }
/** Same as {@link #nearlyEqualsAbs(float, float, float)}, but with doubles. */ public static boolean nearlyEqualsAbs(double a, double b, double maxAbsDiff) { return absoluteDifference(a, b) <= Math.abs(maxAbsDiff); }
/** Same as {@link #relativeDifference(float, float)}, but for doubles. */ public static double relativeDifference(double a, double b) { double absDiff = absoluteDifference(a, b); if (Double.compare(a, b) == 0) { // Shortcut: handles infinities and NaNs. return 0; } else if (a == 0 || b == 0 || absDiff < Double.MIN_NORMAL) { return absDiff / Double.MIN_NORMAL; } else { double maxAbsValue = Math.max(Math.abs(a), Math.abs(b)); return absDiff / maxAbsValue; } }
private String createNumericDataDiffMessage(DataType dt, String name, Number v1, Number v2, IndexIterator iter) { return String.format(" DIFF %s %s: %s != %s; count = %s, absDiff = %s, relDiff = %s %n", dt, name, v1, v2, iter, Misc.absoluteDifference(v1.doubleValue(), v2.doubleValue()), Misc.relativeDifference(v1.doubleValue(), v2.doubleValue())); }
/** * Returns the relative difference between two numbers, i.e. {@code |a - b| / max(|a|, |b|)}. * <p> * For cases where {@code a == 0}, {@code b == 0}, or {@code a} and {@code b} are extremely close, traditional * relative difference calculation breaks down. So, in those instances, we compute the difference relative to * {@link Float#MIN_NORMAL}, i.e. {@code |a - b| / Float.MIN_NORMAL}. * * @param a first number. * @param b second number. * @return the relative difference. * @see <a href="http://floating-point-gui.de/errors/comparison/">The Floating-Point Guide</a> * @see <a href="https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/"> * Comparing Floating Point Numbers, 2012 Edition</a> */ public static float relativeDifference(float a, float b) { float absDiff = absoluteDifference(a, b); if (Float.compare(a, b) == 0) { // Shortcut: handles infinities and NaNs. return 0; } else if (a == 0 || b == 0 || absDiff < Float.MIN_NORMAL) { return absDiff / Float.MIN_NORMAL; } else { float maxAbsValue = Math.max(Math.abs(a), Math.abs(b)); return absDiff / maxAbsValue; } }