提问人:user3618109 提问时间:10/19/2023 最后编辑:user3618109 更新时间:11/3/2023 访问量:68
Javascript 数字类型 [重复]
Javascript Number type [duplicate]
问:
我正在使用 JavaScript,并试图更好地理解浮点数的工作原理以及为什么 .1 + .2 = .3000000000004(或类似的东西)。我想我非常理解为什么,我只是对如何设置等于 .3 的变量感到困惑。
我的意思是我知道我可以使用 var blah = .3,但我不知道 .3 如何存储在浮点变量中,我希望它会变成类似 .299999999 之类的东西,因为 .3 不能用 2 的负幂表示。如果这是有道理的。
我敢肯定这个问题在其他地方已经得到解答,但我找不到。我可以找到很多关于浮点数学和数字如何工作的解释,但不是这个具体问题。或者,也许您可以将 .3 存储在浮点数中,而我只是误解了某些东西。
答:
...我不知道 .3 如何存储在浮点变量中......
它不能。当出现在源代码中时,它将转换为最接近的可表示值,即 0.2999999999999999988897769753748434595763683319091796875,或者等效于 5,404,319,552,844,595•2−54。.3
In 转换为 0.10000000000000000055511151231257827021181583404541015625 (7,205,759,403,792,794•2−56),并转换为 0.2000000000000000011102230246251565404236316680908203125 (7,205,759,403,792,794•2−55)。.1 + .2
.1
.2
观察到 的结果 , 7,205,759,403,792,794•2−55 等于 2•7,205,759,403,792,794•2−56 = 14,411,518,807,585,588•2−56。因此,如果我们将 的结果相加,在数学上,我们得到 21,617,278,211,378,382•2−56。但是,有效数 21,617,278,211,378,382 太大,无法以浮点格式表示。格式将有效位数限制为 53 位,253 为 9,007,199,254,740,992。.2
.1
.2
为了使有效数足够小,我们将其除以 4 并将指数调整为 2;21,617,278,211,378,382•2−56 = 5,404,319,552,844,595.5•2−54。然而,这种形式的有效数只能是整数,所以我们不能把它作为浮点结果。加法的数学结果必须四舍五入以适合格式。5,404,319,552,844,595.5 在 5,404,319,552,844,595 和 5,404,319,552,844,596 之间等距,规则是将平局四舍五入为偶数,因此加法 and 的浮点结果为 5,404,319,552,844,596•2−54,即 0.3000000000000000444089209850062616169452667236328125。.1
.2
Finally, we have to display that number. By default, JavaScript does not display the actual values of floating-point numbers. This is a shortcoming that contributes to misunderstanding floating-point. By default, JavaScript shows just enough digits to uniquely distinguish the floating-point number if you know the floating-point format. It produces the fewest number of digits (aside from an aesthetic leading in ) that will convert back to the floating-point number being displayed.0
0.3…
Above, we saw that converting to JavaScript’s floating-point format yields 0.299999999999999988897769753748434595763683319091796875. This means that, for 0.3000000000000000444089209850062616169452667236328125, JavaScript will not display , because converts to .2999…875, not to .3000…125. Also , , and cannot be used. To get a numeral that will convert back to 0.3000000000000000444089209850062616169452667236328125, JavaScript produces ..3
.3
.3
.30
.300
.3000
0.30000000000000004
In summary, in :.1 + .2
.1
is converted to the floating-point format, with rounding to fit in the format..2
is converted to the floating-point format, with rounding to fit in the format..1
and are added, with rounding to fit in the floating-point format..2
- When printed, the result is converted to decimal, with enough digits to distinguish the value but fewer than needed to show the actual value, with rounding to the number of digits selected.
That is four roundings for one simple expression.
评论
variable = 0.3
console.log
0.3
0.299999999999999988897769753748434595763683319091796875
0.3
0.30000000000000004
0.3
0.30000000000000004