Javascript bitshift 替代 math.round

2024-01-11

var1=anyInteger
var2=anyInteger

(Math.round(var1/var2)*var2)

上述代码的 JavaScript bitshift 替代语法是什么?

使用整数而不是浮点数

谢谢


[更新] 快速回答:

var intResult = ((((var1 / var2) + 0.5) << 1) >> 1) * var2;

它比Math.round()问题中提供的方法并提供完全相同的值。

根据我的测试,位移速度快了 10% 到 20%。下面是一些比较这两种方法的更新代码。

下面的代码有四个部分:首先,它创建 10,000 组两个随机整数;其次,它在OP的问题中进行一轮循环,存储值以供以后比较并记录执行的总时间;第三,它进行等效的位移,存储值以供以后比较,并记录执行时间;第四,它比较 Round 和 Bit-shift 值以找出任何差异。它应该报告没有异常。

请注意,这应该适用于所有正的非零值。如果代码遇到分母为零,它将引发错误,并且我很确定负值不会正确移位,尽管我还没有测试过。

var arr1 = [],
    arr2 = [],
    arrFloorValues = [],
    arrShiftValues = [],
    intFloorTime = 0,
    intShiftTime = 0,
    mathround = Math.round, // @trinithis's excellent suggestion
    i;

// Step one: create random values to compare
for (i = 0; i < 100000; i++) {
    arr1.push(Math.round(Math.random() * 1000) + 1);
    arr2.push(Math.round(Math.random() * 1000) + 1);
}

// Step two: test speed of Math.round()
var intStartTime = new Date().getTime();
for (i = 0; i < arr1.length; i++) {
    arrFloorValues.push(mathround(arr1[i] / arr2[i]) * arr2[i]);
}
console.log("Math.floor(): " + (new Date().getTime() - intStartTime));

// Step three: test speed of bit shift
var intStartTime = new Date().getTime();
for (i = 0; i < arr1.length; i++) {
    arrShiftValues.push( ( ( ( (arr1[i] / arr2[i]) + 0.5) << 1 ) >> 1 ) * arr2[i]);

}
console.log("Shifting: " + (new Date().getTime() - intStartTime));

// Step four: confirm that Math.round() and bit-shift produce same values
intMaxAsserts = 100;
for (i = 0; i < arr1.length; i++) {
    if (arrShiftValues[i] !== arrFloorValues[i]) {
        console.log("failed on",arr1[i],arr2[i],arrFloorValues[i],arrShiftValues[i])
        if (intMaxAsserts-- < 0) break;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Javascript bitshift 替代 math.round 的相关文章

随机推荐