我想计算变量average
是否与另一个变量trackingAmount
相差某个threshold
是正(+)还是负( - )。
如果average
和trackingAmount
之间的差异(+/-)超过了
threshold
值,然后我想触发一个函数
calcMultiTrack()
示例中的阈值称为trackTolerance
average
可以是正面的,也可以是负面的,trackingAmount
什么是最强大的,(也许优雅在这里是一个更好的词),方式 处理这种情况?
average = average / (selItemsDimArray.length - 1);
var trackingAmount = 3
var trackTolerance = 0.2
//If number is positive
if (average >= 0) {
if (average < (trackingAmount - trackTolerance) || average > (trackingAmount + trackTolerance)) {
calcMultiTrack(); //This is the function I want to call if the numbers are not the same(threshold value applies)
console.log("Positive average that differs with trackingAmount by more than +- tolerance");
}
}
//Else number is negative
else {
if (average < (-(trackingAmount - trackTolerance)) || average > (-(trackingAmount + trackTolerance))) {
calcMultiTrack();
console.log("Negative average that differs with trackingAmount by more than +- tolerance");
}
}
答案 0 :(得分:3)
绝对值函数是计算两个实数之间距离的理想方法。
Math.abs(average - trackingAmount) < threshold
答案 1 :(得分:2)
通常这种比较是用
完成的Math.abs(x - expected) < threshold
如果值具有绝对意义且原点是任意的(例如位置)。
如果否则值为正且基于零(例如,权重),则通常使用相对距离
Math.abs(x - expected) / expected < threshold
例如,使用threshold = 0.1
表示10%
错误。