JavaScript 的整数相加问题

Integer adding problems with JavaScript

我们目前正在实验室学习 JavaScript,我们刚刚创建了一个简单的斐波那契函数,用于计算斐波那契数列的前 100 个数字。

function fibo(stop) {
  let counter = 0;
  let first = 1;
  let second = 1;
  let third = 0;
  console.log(third);
  console.log(second);
  console.log(first);
  while (true) {
    third = second;
    second = first;
    first = second + third;
    counter++;
    if (counter >= stop) {
      break;
    }
    console.log(first);
  }
}

fibo(100);

现在当我 运行 它有一个部分只是神奇地将数字加在一起错误。

当我在 JavaScript 中将这两个数字分别相加时,我得到与屏幕截图中第三行相同的答案。然而,当我在计算器上重做加法时,它显示 14 472 334 024 676 221 而不是 14 472 334 024 676 220。我的第一个猜测是它与整数溢出有关,但又是 log2(14472334024676220) = 53.684... 这意味着在 64 位整数中它没有溢出。为什么会这样?它从何而来?我试着问过我的老师,但他不知道。

处理整数时,最大安全整数(即 n + 1 !== n)是 9007199254740991,即 2^53 - 1

Javasacript 数字是 64 位浮点数,这并不意味着整数

使用 BigInts - 要初始化 BigInt,您可以使用 n 数字后缀,如下所示

function fibo(stop) {
  let counter = 0;
  let first = 1n;
  let second = 1n;
  let third = 0n;
  console.log(third.toString());
  console.log(second.toString());
  console.log(first.toString());
  while (true) {
    third = second;
    second = first;
    first = second + third;
    counter++;
    if (counter >= stop) {
      break;
    }
    console.log(first.toString());
  }
}

fibo(100);

注意:Stack Snippet console.log 无法记录 BigInt,这就是我放置 .toString()

的原因