gpt4 book ai didi

javascript - 将 0.02 添加到 javascript 中的数字会导致不正确的值

转载 作者:行者123 更新时间:2023-11-30 12:23:05 28 4
gpt4 key购买 nike

我试图通过小数间隔获取从 minmax 的数字数组,在本例中为 0.02,例如:1.00 , 1.02, 1.04, 1.06

下面的代码在 1.14 处开始中断:

function getOptions(min, max, interval) {
var options = [];

for (var i = min; i <= max; i += interval) {
options.push(i);
}

return options;
}

var options = getOptions(1.0, 1.4, 0.02);

此时,options 就像:

[
1,
1.02,
...
1.12,
1.1400000000000001,
1.1600000000000001
...
]

是什么原因造成的,我该如何解决?

最佳答案

根据 What Every Programmer Should Know About Floating-Point Arithmetic :

internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

When the code is compiled or interpreted, your “0.1” is already rounded to the nearest number in that format, which results in a small rounding error even before the calculation happens.

对于 Javascript specifically :

JavaScript numbers are really just floating points as specified by IEEE-754. Due to inadequecies when representing numbers in base-2, as well as a finite machine, we are left with a format that is filled with rounding errors. This article explains those rounding errors and why errors occur. Always use a good library for numbers instead of building your own

我在这方面取得了一些成功 BigDecimal port越小,越快big.js .

关于javascript - 将 0.02 添加到 javascript 中的数字会导致不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30379856/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com