Math オブジェクトは、いくつかの数学関数のための名前空間として使用されます。この章では、その概要を説明します。
Math のプロパティは、次のとおりです。
Math.E
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E
Math.PI
Math.SQRT1_2
Math.SQRT2
Math の数値関数には、次のものがあります。
Math.abs(x)
x の絶対値を返します。Math.ceil(x)
> Math.ceil(3.999) 4 > Math.ceil(3.001) 4 > Math.ceil(-3.001) -3 > Math.ceil(3.000) 3
浮動小数点数を整数に変換する方法の詳細については、「整数への変換」を参照してください。
Math.exp(x)
Math.E) です。これは Math.log() の逆関数です。Math.floor(x)
> Math.floor(3.999) 3 > Math.floor(3.001) 3 > Math.floor(-3.001) -4 > Math.floor(3.000) 3
浮動小数点数を整数に変換する方法の詳細については、「整数への変換」を参照してください。
Math.log(x)
x の自然対数 (底はオイラー定数) ln(x) を返します。これは Math.exp() の逆関数です。Math.pow(x, y)
xy を返します。x を y 乗した値です。
> Math.pow(9, 2) 81 > Math.pow(36, 0.5) 6
Math.round(x)
x を最も近い整数に丸めた値を返します (2 つの整数の間にある場合は大きい方の整数)。
> Math.round(3.999) 4 > Math.round(3.001) 3 > Math.round(3.5) 4 > Math.round(-3.5) -3
浮動小数点数を整数に変換する方法の詳細については、「整数への変換」を参照してください。
Math.sqrt(x)
, x の平方根を返します。
> Math.sqrt(256) 16
三角関数のメソッドは、角度をラジアンで受け取り、返します。必要に応じて変換を実装する方法を次の関数で示します。
度からラジアンへの変換
functiontoRadians(degrees){returndegrees/180*Math.PI;}
これは対話の例です
> toRadians(180) 3.141592653589793 > toRadians(90) 1.5707963267948966
ラジアンから度への変換
functiontoDegrees(radians){returnradians/Math.PI*180;}
これは対話の例です
> toDegrees(Math.PI * 2) 360 > toDegrees(Math.PI) 180
三角関数のメソッドは次のとおりです
Math.acos(x)
x の逆コサインを返します。Math.asin(x)
x の逆サインを返します。Math.atan(x)
x の逆タンジェントを返します。Math.atan2(y, x)
Math.cos(x)
x のコサインを返します。Math.sin(x)
x のサインを返します。Math.tan(x)
x のタンジェントを返します。以下は、残りの Math 関数です。
Math.min(x1?, x2?, ...)
パラメータの中で最も小さい数値を返します。
> Math.min() Infinity > Math.min(27) 27 > Math.min(27, -38) -38 > Math.min(27, -38, -43) -43
apply() を介して配列で使用します (「func.apply(thisValue, argArray)」を参照してください)。
> Math.min.apply(null, [27, -38, -43]) -43
Math.max(x1?, x2?, ...)
パラメータの中で最も大きい数値を返します。
> Math.max() -Infinity > Math.max(7) 7 > Math.max(7, 10) 10 > Math.max(7, 10, -333) 10
apply() を介して配列で使用します (「func.apply(thisValue, argArray)」を参照してください)。
> Math.max.apply(null, [7, 10, -333]) 10
Math.random()
擬似乱数 r (0 ≤ r < 1) を返します。次の関数は、Math.random() を使用してランダムな整数を計算します。
/*** Compute a random integer within the given range.** @param [lower] Optional lower bound. Default: zero.* @returns A random integer i, lower ≤ i < upper*/functiongetRandomInteger(lower,upper){if(arguments.length===1){upper=lower;lower=0;}returnMath.floor(Math.random()*(upper-lower))+lower;}