By Alvin Alexander. Last updated: February 8, 2017
As a quick note, here’s the source code for a Java “approximately equal” function that I use in an Android application:
/** * determine whether two numbers are "approximately equal" by seeing if they * are within a certain "tolerance percentage," with `tolerancePercentage` given * as a percentage (such as 10.0 meaning "10%"). * * @param tolerancePercentage 1 = 1%, 2.5 = 2.5%, etc. */ public static boolean approximatelyEqual(float desiredValue, float actualValue, float tolerancePercentage) { float diff = Math.abs(desiredValue - actualValue); // 1000 - 950 = 50 float tolerance = tolerancePercentage/100 * desiredValue; // 20/100*1000 = 200 return diff < tolerance; // 50<200 = true }
You call the function like this:
boolean closeEnough = approximatelyEqual(1000, 950, 20);
Hopefully the comments describe the function well enough, so I’ll leave it at that, except for two related notes:
- The line that determines the tolerance uses Java mixed-type arithmetic rules.
- (The original last line of the function uses the Java ternary operator syntax.)