计算1000.1+0.2
,把尾数前面隐含的 1 位也写出来,也加上 Guard bit 、Round bit 和 Sticky bit
1000.1 =
0 10000001000 1.1111010000001100110011001100110011001100110011001101 000
0.2 =
0 01111111100 1.1001100110011001100110011001100110011001100110011010 000
10000001000-01111111100=1100
,即 12 。0.0000000000011001100110011001100110011001100110011001 100
1.1111010000001100110011001100110011001100110011001101 000 +
0.0000000000011001100110011001100110011001100110011001 100
==========================================================
1.1111010000100110011001100110011001100110011001100110 100
0 10000001000 1.1111010000100110011001100110011001100110011001100110 100
100
中间值,向偶数舍入,使最低有效位为 0
0 10000001000 1111010000100110011001100110011001100110011001100110
为啥这样算出来的值和 JavaScript 中1000.1+0.2
差 1 个 bit ? JS 中得到的值是下面这个
0 10000001000 1111010000100110011001100110011001100110011001100111
和之前算的就差 1 个 bit
0 10000001000 1111010000100110011001100110011001100110011001100110
let d = new DataView(new ArrayBuffer(8));
d.setFloat64(0, 1000.1+0.2);
console.log(d.getBigUint64(0).toString(16));
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.