JavaScriptで立方根計算!Math.cbrt()関数入門
投稿日 2025年02月07日 更新日 2025年02月07日
JavaScriptで数値の立方根(キュービックルート)を求めたい場合、`Math.cbrt()`関数を使用します。この記事では、`Math.cbrt()`の基本的な使い方から実践的な例まで詳しく解説します。
Math.cbrt()関数の基本
`Math.cbrt()`は数値の立方根を計算するJavaScriptの組み込み関数です。引数に与えた数値の3乗根を返します。
// 基本的な使い方
console.log(Math.cbrt(27)); // 出力: 3
console.log(Math.cbrt(8)); // 出力: 2
console.log(Math.cbrt(1)); // 出力: 1
特徴と注意点
1. 負の数にも対応
console.log(Math.cbrt(-27)); // 出力: -3
console.log(Math.cbrt(-8)); // 出力: -2
2. 小数点の計算も可能
console.log(Math.cbrt(125.0)); // 出力: 5
console.log(Math.cbrt(0.125)); // 出力: 0.5
3. 0や特殊な値の処理
console.log(Math.cbrt(0)); // 出力: 0
console.log(Math.cbrt(-0)); // 出力: -0
console.log(Math.cbrt(NaN)); // 出力: NaN
console.log(Math.cbrt(Infinity)); // 出力: Infinity
実践的な使用例
例1:体積から辺の長さを求める
function getCubeSideLength(volume) {
return Math.cbrt(volume);
}
console.log(getCubeSideLength(27)); // 出力: 3
例2:小数点以下の桁数を指定
function cbrtWithPrecision(num, precision = 2) {
return Number(Math.cbrt(num).toFixed(precision));
}
console.log(cbrtWithPrecision(30, 3)); // 出力: 3.107
ブラウザ互換性
`Math.cbrt()`は比較的新しい関数ですが、現代の主要なブラウザでは広くサポートされています。Internet Explorer 11以降、Chrome 38以降、Firefox 25以降、Safari 8以降で使用可能です。
代替方法
古いブラウザをサポートする必要がある場合は、以下のようなポリフィルを使用できます:
if (!Math.cbrt) {
Math.cbrt = function(x) {
return x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3);
};
}
まとめ
`Math.cbrt()`は立方根を簡単に計算できる便利な関数です。数学的な計算や3D関連の処理で活用できます。主要なブラウザで広くサポートされており、使いやすい API を提供しています。
関連記事

新着記事
4
5
6
関連記事
4
5
6


60秒で完了