
目次
- よく使う計算式
- Math関数
- Math.floor() - 与えた数値以下の最大の整数を返す
- Math.trunc() - 与えた数値の小数点以下を切り捨てて整数を返す
- Math.round() - 与えた数値を四捨五入して整数を返す
- Math.ceil() - 与えた数値以上の最小の整数を返す
- Math.abs() - 与えた数値の絶対値を返す
- Math.sqrt() - 与えた数値の平方根を返す
- Math.cbrt() - 与えた数値の立方根を返す
- Math.pow() - 与えた数値(第一引数)を与えた数値(第二引数)で冪乗して返す
- Math.atan2() - (0, 0) から点 (y(第一引数), x(第二引数)) までの角度を返す(ラジアン単位)
- Math.min() - 与えた数値の中から最小の値を返す
- Math.max() - 与えた数値の中から最大の値を返す
随時更新。
よく使う計算式
2点間の距離を出す
三平方の定理で直角三角形の斜辺の長さを出す。
c^2 = a^2 + b^2
const position1 = {
x: 10,
y: 10
};
const position2 = {
x: 20,
y: 20
};
// 差分を出して
const x = position1.x - position2.x;
const y = position1.y - position2.y;
// 三平方の定理を使うよ
const distance = Math.sqrt(x * x + y * y);
2点間の角度を出す(ラジアン)
const position1 = {
x: 10,
y: 10
};
const position2 = {
x: 20,
y: 20
};
console.log(Math.atan2(position2.y - position1.y, position2.x - position1.x));
// 0.7853981633974483
ラジアン(弧度法)を度(度数法)に変換する
度 = ラジアン × (180 ÷ 円周率)
const degree = radian * (180 / Math.PI);
Math関数
Math.floor() - 与えた数値以下の最大の整数を返す
console.log(Math.floor(5.9));
// 5
console.log(Math.floor(-5.1));
// -6
Math.trunc() - 与えた数値の小数点以下を切り捨てて整数を返す
console.log(Math.trunc(10.55));
// 10
Math.round() - 与えた数値を四捨五入して整数を返す
console.log(Math.round(0.9));
// 1
Math.ceil() - 与えた数値以上の最小の整数を返す
console.log(Math.ceil(0.95));
// 1
console.log(Math.ceil(1.25));
// 2
Math.abs() - 与えた数値の絶対値を返す
console.log(Math.abs(5));
// 5
console.log(Math.abs(-5));
// 5
Math.sqrt() - 与えた数値の平方根を返す
三平方の定理とかと使うと便利
console.log(Math.sqrt(25));
// 5
Math.cbrt() - 与えた数値の立方根を返す
console.log(Math.cbrt(8));
// 2
console.log(Math.cbrt(27));
// 3
Math.pow() - 与えた数値(第一引数)を与えた数値(第二引数)で冪乗して返す
console.log(Math.pow(5, 2));
// 25
Math.atan2() - (0, 0) から点 (y(第一引数), x(第二引数)) までの角度を返す(ラジアン単位)
console.log(Math.atan2(10, 10));
// 0.7853981633974483
console.log(Math.atan2(10, 10) * (180 / Math.PI)); // 度数法に変換してみる
// 45
発展 - ある点からある点への角度を返す(ラジアン単位)
const position1 = {
x: 10,
y: 10
};
const position2 = {
x: 20,
y: 20
};
console.log(Math.atan2(position2.y - position1.y, position2.x - position1.x));
// 0.7853981633974483
Math.min() - 与えた数値の中から最小の値を返す
console.log(Math.min(1, 2, 3));
// 1
console.log(Math.min(-1, -2, -3));
// -3
Math.max() - 与えた数値の中から最大の値を返す
console.log(Math.max(1, 2, 3));
// 3
console.log(Math.max(-1, -2, -3));
// -1