Uint8ClampedArray 的奇怪舍入行为
Strange rounding behaviour of Uint8ClampedArray
我发现 Javascript 的 Uint8ClampedArray 的舍入行为对我来说没有意义。根据 the spec,将非整数设置为 Uint8ClampedArray "the nearest integer will be set"。
奇怪的是,对于任何值 i+0.5
(其中 i
是整数),如果 i
为奇数,则值将向上舍入,如果 i
是偶数。
这是一个简单的例子来展示行为:
var clampedArr = new Uint8ClampedArray(1);
for (var i = 0; i < 6; i++) {
var val = i + 0.5;
clampedArr[0] = val;
console.log(val + " -> " + clampedArr[0]);
}
输出为
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
4.5 -> 4
5.5 -> 6
Here is a jsfiddle 上面的代码。
能否以某种方式解释此行为,因为它不同于 Math.round()
?
我对评论不满意,因为它们没有解释与 Math.round()
使用的 Javascript 标准舍入行为的区别。因此,我挖得更深一些。
Mozilla's documentation for Uint8ClampedArray 只是说 "if you specify a non-integer, the nearest integer will be set",没有指定舍入类型。 Javascript 程序员(比如我自己)可能会假设四舍五入与 Math.round()
中的相同
Microsoft's documentation for Uint8ClampedArray 更精确并添加了以下注释:"Values in a Uint8ClampedArray object are rounded to the nearest even value, which is called banker's rounding." 这清楚地表明与 Math.round()
不同的舍入使用过。
我发现 Javascript 的 Uint8ClampedArray 的舍入行为对我来说没有意义。根据 the spec,将非整数设置为 Uint8ClampedArray "the nearest integer will be set"。
奇怪的是,对于任何值 i+0.5
(其中 i
是整数),如果 i
为奇数,则值将向上舍入,如果 i
是偶数。
这是一个简单的例子来展示行为:
var clampedArr = new Uint8ClampedArray(1);
for (var i = 0; i < 6; i++) {
var val = i + 0.5;
clampedArr[0] = val;
console.log(val + " -> " + clampedArr[0]);
}
输出为
0.5 -> 0
1.5 -> 2
2.5 -> 2
3.5 -> 4
4.5 -> 4
5.5 -> 6
Here is a jsfiddle 上面的代码。
能否以某种方式解释此行为,因为它不同于 Math.round()
?
我对评论不满意,因为它们没有解释与 Math.round()
使用的 Javascript 标准舍入行为的区别。因此,我挖得更深一些。
Mozilla's documentation for Uint8ClampedArray 只是说 "if you specify a non-integer, the nearest integer will be set",没有指定舍入类型。 Javascript 程序员(比如我自己)可能会假设四舍五入与 Math.round()
Microsoft's documentation for Uint8ClampedArray 更精确并添加了以下注释:"Values in a Uint8ClampedArray object are rounded to the nearest even value, which is called banker's rounding." 这清楚地表明与 Math.round()
不同的舍入使用过。