pow関数

広告

pow関数は累乗を計算した結果を返します。

累乗を計算した結果を返します。

パラメータ:
  x  底
  n  指数
戻り値:
  xのn乗を計算した結果

1番目の引数に指定した底の数を、2番目の引数に指定した指数分だけ累乗した結果を返します。

一般にxのn乗はxnと記述し次のようにxをn回乗算したものです。

xn = x × x × x ... × x

指数が負の値だった場合、次のように変換できます。

x-1 = 1 / x
x-2 = 1 / x2
x-n = 1 / xn

指数が0だった場合は底の値に関わらず累乗の結果は1となります。

指数が整数ではなかった場合、次のように変換できます。

x1/2 = xの平方根
x1/3 = xの3乗根
x1/n = xのn乗根
xm/n = (xのn乗根)m

※この時、xが負の値だと結果が複素数や虚数になる場合があります。その場合はNaNが返されます。

実際には次のように使用します。

var num = Math.pow(2, 3);

上記の場合、変数numには8が代入されます。

サンプルコード

では簡単なサンプルで試してみます。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>JavaScript テスト</title>
</head>
<body>

<script type="text/javascript" src="./js/script17_1.js">
</script>

</body>
</html>
function print(str){
  document.write(str + "<br />");
}

document.write("<p>");

print("Math.pow(3, 2) = " + Math.pow(3, 2));
print("Math.pow(3, 3) = " + Math.pow(3, 3));
print("Math.pow(3, -1) = " + Math.pow(3, -1));
print("Math.pow(3, -2) = " + Math.pow(3, -2));
print("Math.pow(3, 0) = " + Math.pow(3, 0));
print("Math.pow(3, 0.75) = " + Math.pow(3, 0.75));
print("Math.pow(-3, 3) = " + Math.pow(-3, 3));
print("Math.pow(-3, 0.5) = " + Math.pow(-3, 0.5));

document.write("</p>");

上記を実際にブラウザ見てみると次のように表示されます。

p17-1

( Written by Tatsuo Ikura )