- Home ›
- JavaScript入門 ›
- Mathクラス ›
- HERE
sqrt関数
広告
sqrt関数は平方根を計算した結果を返します。
Math.sqrt(val)
平方根を計算した結果を返します。 パラメータ: val 数値または他の値 戻り値: 引数の平方根
引数に指定した値の平方根を計算します。平方根とは a = b2 が成り立つ時、bをaの平方根と呼びます。
実際には次のように使用します。
var num = Math.sqrt(9);
上記の場合、変数numには3が代入されます。
数値以外の値が引数に与えられた場合は数値に変換した上で平方根を計算します。引数に負の値が指定された場合や、NaNが指定された場合には平方根の結果としてNaNが返されます。
なおMathクラスには平方根に関する定数が定義されています。
Math.SQRT2 2の平方根 Math.SQRT1_2 1/2の平方根
サンプルコード
では簡単なサンプルで試してみます。
<!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/script16_1.js"> </script> </body> </html>
function print(str){ document.write(str + "<br />"); } document.write("<p>"); print("Math.sqrt(4) = " + Math.sqrt(4)); print("Math.sqrt(6) = " + Math.sqrt(6)); print("Math.sqrt(8) = " + Math.sqrt(8)); print("Math.sqrt(9) = " + Math.sqrt(9)); print("Math.sqrt(12.44) = " + Math.sqrt(12.44)); print("Math.sqrt(-2) = " + Math.sqrt(-2)); print("Math.sqrt(NaN) = " + Math.sqrt(NaN)); document.write("</p>");
上記を実際にブラウザ見てみると次のように表示されます。
( Written by Tatsuo Ikura )