A Java “approximately equal” method (function)

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:

Permalink

Thanks for your technical posts,
I have a question about style, here.
Why do yo write :
return (diff < tolerance) ? true : false;
instead of simply :
return diff < tolerance;

For me the later, when you used to read code, is clearer.

N.B. I had some difficulty with the Preview. I needed to submit blindly

Thank you for your comment. The short answer is that I wrote this when I was tired. I also prefer your code, and updated the function to reflect that.

Also, I’m sorry about how the comment-submission form works here. I’m using a content management system, and I haven’t looked into how to override the default comments system.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.