Java\"近似相等\"方法(函数)

・1 分钟阅读

>

快速说明,这个是我在Android应用程序中使用的Java\"近似相等\"函数的源代码:




/**
 * 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
}

你可以这样调用函数:




boolean closeEnough = approximatelyEqual(1000, 950, 20);

Xn_warm profile image