JavaScript/Math/acos

カテゴリ:Book:JavaScript#Math/acos%20

Math.acos(x) は、引数 x の逆余弦(アークコサイン)を返します。これは、x の値に対応する角度をラジアン単位で返します[1]

  • 引数 xNaN の場合、NaN を返します。
  • 引数 x1 より大きいか -1 より小さい場合、NaN を返します。
  • 引数 x1 の場合、+0 を返します。
  • 引数 x-1 の場合、π を返します。

逆余弦を計算するプログラム

以下のプログラムは、ユーザーが入力した値の逆余弦を計算します。

const f = p => {
  for (;;) {
    a = prompt(`${p}は何ですか?`);
    if (!isNaN(a) && a >= -1 && a <= 1)
      return a;
    alert(`${p}に、入力ミスがあります。 "${a}"`);
  }
}

for (;;) {
  const x = f("値");
  const acos = Math.acos(x);
  if (!isNaN(acos)) {
    alert(`${x} の逆余弦は ${acos.toFixed(3)} ラジアンです。`);
    break;
  }
  alert("入力が大きすぎます。");
}

このプログラムでは、Math.acos を使用して値の逆余弦を計算しています。ユーザーが入力した値が NaNInfinity の場合、適切に処理されます。

逆余弦関数のグラフを描画するプログラム

以下のプログラムは、逆余弦関数のグラフを描画します。

const canvas = document.createElement('canvas');
document.body.appendChild(canvas);
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 400;

const xScale = canvas.width / 2;
const yScale = canvas.height / Math.PI;

ctx.beginPath();
ctx.moveTo(0, canvas.height);

for (let x = -1; x <= 1; x += 0.01) {
  const y = Math.acos(x);
  const canvasX = (x + 1) * xScale;
  const canvasY = canvas.height - y * yScale;
  ctx.lineTo(canvasX, canvasY);
}

ctx.strokeStyle = 'blue';
ctx.lineWidth = 2;
ctx.stroke();

このプログラムでは、Math.acos を使用して逆余弦関数のグラフを描画しています。xScaleyScale は、グラフのスケーリングを調整するための変数です。

注意点

  • 引数の範囲: Math.acos の引数 x は、-1 から 1 の範囲でなければなりません。この範囲外の値を指定すると、NaN が返されます。
  • 戻り値の範囲: Math.acos の戻り値は、0 から π の範囲です。
  • 精度: 浮動小数点演算の特性上、Math.acos の結果には微小な誤差が含まれることがあります。

脚註

  1. これは、数学的には cos(y) = x となるような角度 y を返します。

外部リンク

カテゴリ:Book:JavaScript#Math/acos%20 カテゴリ:JavaScript
カテゴリ:Book:JavaScript カテゴリ:JavaScript カテゴリ:Pages using the JsonConfig extension