我有一个表达式,用于通过在两个值之间进行插值来估计百分位数。
windowMin + (currentPercentile - lastPercentile) * (windowMax - windowMin) / (percentile - lastPercentile)
这给了我非常好的真实世界结果。但是,在我的单元测试中,我无法断言事情是否正常工作,因为我总是遇到严重的舍入错误。
在三个测试用例中,我尝试获得第 40th、第 50 和第 60 个百分位数,从而产生这些计算:
1 + (0.4 - 0.3333333333333333) * (2 - 1) / (0.6666666666666666 - 0.3333333333333333)
1 + (0.5 - 0.3333333333333333) * (2 - 1) / (0.6666666666666666 - 0.3333333333333333)
1 + (0.6 - 0.3333333333333333) * (2 - 1) / (0.6666666666666666 - 0.3333333333333333)
这会产生:
{
"0.4": 1.2000000000000002,
"0.5": 1.5,
"0.6": 1.8
}
我的断言失败了,我的断言正在寻找第 40 个 百分位数的 1.2
。
有没有办法重构这个表达式以提高所有情况下的准确性?如果没有,是否有一种简单的方法可以使用 chai 断言解决此问题?
最佳答案
这些舍入误差是 float 学的一个特征。
一个可能的解决方案可能是在返回结果之前将 .toPrecision()
应用于您的计算:
var result = windowMin + (currentPercentile - lastPercentile) * (windowMax - windowMin) / (percentile - lastPercentile);
return result.toPrecision(6); // returns six significant figures
或者可能是toFixed()
:
return result.toFixed(2); // returns two decimal places.
关于javascript - 有没有办法提高这个表达式的浮点精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18940378/