紀錄工作經驗、相關知識,解決技術相關問題。

Javascript

JS Math.cbrt 用法:立方根與負數

JS Math.cbrt 用法:立方根與負數 特色圖片

Math.cbrt() 是 JavaScript 計算立方根(cube root)的靜態方法:傳入一個數字,回傳「自乘三次後等於該數」的那個數。

白話一點,Math.cbrt(27) 問的是「哪個數乘三次會得到 27」,答案是 3。

語法

Math.cbrt(x)
  • x:一個數字。
  • 回傳值:x 的立方根。

MDN 給的數學定義:Math.cbrt(x) 等於唯一一個滿足 y³ = x 的 y。cbrt() 是 Math 的靜態方法,一律寫成 Math.cbrt(),不需要也不能 new Math()。

基本用法

console.log(Math.cbrt(-Infinity)); // -Infinity
console.log(Math.cbrt(-1));        // -1
console.log(Math.cbrt(-0));        // -0
console.log(Math.cbrt(0));         // 0
console.log(Math.cbrt(1));         // 1
console.log(Math.cbrt(2));         // 1.2599210498948732
console.log(Math.cbrt(Infinity));  // Infinity

整理成對照表:

輸入結果
-Infinity-Infinity
-1-1
-0-0
00
11
21.2599210498948732
InfinityInfinity
console.log(Math.cbrt(64));  // 4
console.log(Math.cbrt(27));  // 3
console.log(Math.cbrt(-8));  // -2

負數也能算

立方根對負數有解(-2 乘三次是 -8),所以 Math.cbrt() 可以直接處理負數;平方根沒有,Math.sqrt() 遇到負數會得到 NaN:

console.log(Math.cbrt(-8)); // -2
console.log(Math.sqrt(-8)); // NaN

與 x ** (1 / 3) 的差別

用冪運算也能算立方根,但結果不一定一樣:

console.log(Math.cbrt(27));        // 3
console.log(27 ** (1 / 3));        // 3
console.log(Math.cbrt(1000));      // 10
console.log(1000 ** (1 / 3));      // 9.999999999999998
console.log((-8) ** (1 / 3));      // NaN

1 / 3 無法用浮點數精確表示,所以 1000 ** (1 / 3) 差了一點點;負數的 (-8) ** (1 / 3) 在這個環境得到 NaN。需要立方根時,直接用 Math.cbrt()。

實用範例:由體積求正方體邊長

function cubeSide(volume) {
  return Math.cbrt(volume);
}

console.log(cubeSide(125));  // 5
console.log(cubeSide(0.001)); // 0.1

注意事項

  1. 負數不會得到 NaN:和 Math.sqrt() 不同,負數有立方根。
  2. 結果可能是近似值:不是完全立方的數(例如 2)會得到浮點數近似值,比較時用差距小於某個門檻判斷。
  3. 精度依引擎而異:MDN 說明 Math 的許多函式精度依實作而異,不同環境的結果最後幾位可能不同。
  4. 舊環境相容性:如果要支援很舊的瀏覽器,可查 MDN 頁面上的相容性表,並參考頁面列出的 polyfill。

補充說明:範例輸出為 Node.js v22.20.0 的執行結果。相關方法還有 Math.pow()(冪運算)與 Math.sqrt()(平方根)。

參考資料與延伸閱讀

發佈留言