JavaScript - 大整數 (BigInt)



大整數 (BigInt)

JavaScript 中的 BigInt 資料型別是一種數值基元型別,可以表示任意大小的整數。這與 Number 資料型別不同,Number 資料型別只能表示介於 -(253 - 1) 和 253 - 1 之間的整數。

JavaScript 為動態網頁應用程式提供動力,傳統上使用 Number 型別根據廣泛採用的 IEEE-754 標準的雙精度浮點格式表示數字。此標準施加了一個重要的限制:它只能精確地表示最多 253 - 1 作為其最大安全整數。但是,超過此數值閾值會開始降低數值的保真度,並在關鍵計算中引入潛在的不準確性。

JavaScript 引入 BigInt 資料型別是為了解決這些限制;顧名思義,BigInt 解決了有限精度的缺點。這種功能在各種場景中被證明是不可或缺的,尤其是在密碼演算法、財務計算和需要高度精度的複雜數學運算等領域:它允許表示任意精度的整數,這是一項重大進步。

宣告和初始化

您可以使用後跟 n 字尾的數字字面量或使用 BigInt() 建構函式來建立 BigInt。

const bigIntLiteral = 123n;
const anotherBigInt = BigInt(456);

需要注意的是,嘗試混合使用普通數字和 BigInt 而沒有顯式轉換可能會導致錯誤。

基本運算

BigInt 支援標準算術運算,如加法、減法、乘法和除法。執行運算時,兩個運算元都必須是 BigInt 型別。

const a = 123n;
const b = 456n;
const sum = a + b; // 579n
const product = a * b; // 56088n

比較

可以使用標準比較運算子(例如 <, >, <=, >= 和 ===)比較 BigInt 值。

const a = 123n;
const b = 456n;
a > b; // false
a === b; // false

轉換

可以在 BigInt 和普通數字之間進行轉換,但請記住,對於非常大的 BigInt 值,可能會損失精度。

const bigIntValue = BigInt("12345678901234567890");
const regularNumber = Number(bigIntValue);
const bigIntValue = BigInt("12345678901234567890");
const regularNumber = Number(bigIntValue);

示例

示例 1:簡單的 BigInt 算術運算

在這個例子中,我們演示了兩個 BigInt 數字 num1 和 num2 的加法和乘法,它們的值分別是 123n 和 456n。透過能夠精確表示大整數而不會損失精度,BigInt 克服了普通 JavaScript 數字的一個潛在缺點。

<!DOCTYPE html>
<html>
<body>
   <h2>Simple BigInt Arithmetic</h2>
   <p id="result"></p>
   <script>
      const num1 = 123n;
      const num2 = 456n;

      const sum = num1 + num2;
      const product = num1 * num2;

      document.addEventListener("DOMContentLoaded", function () {
         document.getElementById("result").innerText = 
			`Sum of ${num1} & ${num2} is ${sum} and their product: ${product}`;
      });
   </script>
</body>
</html>

示例 2:使用 BigInt 的斐波那契數列生成器

斐波那契數列:一系列數字,其中每個數字都是其前兩個數字之和;使用 BigInt 來處理超過普通 JavaScript 數字精度限制的較大值。透過 generateFibonacci 函式,陣列用作這些序列值的儲存,即使對於具有很大數值大小的項也能保證精確計算。

<!DOCTYPE html>
<html>
<body>
   <h2>Fibonacci Sequence</h2>
   <p id="result"></p>
   <script>
      function generateFibonacci(n) {
         const sequence = [0n, 1n];
         for (let i = 2; i <= n; i++) {
            sequence[i] = sequence[i - 1] + sequence[i - 2];
         }
         return sequence;
      }

      document.addEventListener("DOMContentLoaded", function () {
         const result = generateFibonacci(20); 
         document.getElementById("result").innerText = "Fibonacci Sequence of 1st 20 terms: " + result.join(", ");
      });
   </script>
</body>
</html>

示例 3:使用 BigInt 的階乘計算器

階乘是小於或等於該數字的所有正整數的乘積。為了找到階乘,我們使用了 BigInt。對於像 5 和 10 這樣的較小數字,普通數字可以工作,但是當我們必須找到 10000 的階乘時會發生什麼情況,輸出將過於龐大。因此,BigInt 將來拯救我們。在這個例子中,我們使用迴圈來計算 20n 的階乘。

<!DOCTYPE html>
<html>
<body>
   <h2>Factorial of a Large Number</h2>
   <p id="result"></p>
   <script>
      function calculateFactorial() {
         const num = 20n; // Calculate factorial of 20
         let result = 1n;

         for (let i = 2n; i <= num; i++) {
            result *= i;
         }
         document.getElementById("result").innerText = "Factorial of 20 is " + result;
      }
      document.addEventListener("DOMContentLoaded", function () {
         calculateFactorial();
      });
   </script>
</body>
</html>

示例 4:BigInt 顏色方塊

本例中,我們利用 BigInt 生成預定義引數範圍內的隨機顏色,並將其應用於 colorSquare 進行演示。隨機顏色的生成涉及乘法運算:透過 Math.random() 獲取 0 到 1 之間的浮點數,然後將其乘以最大顏色值。隨後,我們使用 Math.floor() 將結果向下取整到最接近的整數,然後再使用 BigInt() 將其轉換為 BigInt。生成的 BigInt 隨後被轉換為十六進位制字串並返回。

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: Arial, sans-serif;
      }
      #colorSquare {
         width: 400px;
         height: 200px;
         border: 2px solid #000;
      }
   </style>
</head>
<body>
   <h2>BigInt Color Example</h2>
   <div id="colorSquare"></div>
   <script> 
      function generateRandomColor() {
         const maxColorValue = 16777215n; // 0xFFFFFF in hexadecimal
         const randomColor = BigInt(Math.floor(Math.random() * Number(maxColorValue)));
         return `#${randomColor.toString(16).padStart(6, '0')}`;
      }
      const colorSquare = document.getElementById('colorSquare');
      colorSquare.style.backgroundColor = generateRandomColor();
   </script>
</body>
</html>

BigInt 的錯誤處理

此程式碼演示了 BigInt 與普通數字相加的特殊情況。在 JavaScript 中,我們需要顯式地將數字轉換為 BigInt。當我們嘗試將 42(普通數字)與 42n(或 BigInt)相加時,它會丟擲一個錯誤,該錯誤在 try catch 的幫助下被捕獲並顯示在螢幕上。

<!DOCTYPE html>
<html>
<body>
   <h2>Adding BigInt & Regular Number</h2>
   <div id="output"></div>
   <script>
      const regularNumber = 42;
      const bigIntValue = BigInt(regularNumber); // Explicit conversion

      document.getElementById("output").innerHTML = 
	   `<p>Regular Number: ${regularNumber}</p>`+
      `<p>BigInt Value: ${bigIntValue}</p>` +
      `<p>Regular Number + BigInt Value results in:</p>`;

      try {
         const result = regularNumber + bigIntValue;
         document.getElementById("output").innerHTML += `Result: ${result}`;
      } catch (e) {
         document.getElementById("output").innerHTML += `Error: ${e}`;
      }
   </script>
</body>
</html>
廣告