JavaScript/Math/atan

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

Math.atan(x) は、引数 x の逆正接(アークタンジェント)を返します。これは、x の値に対応する角度をラジアン単位で返します[1]

  • 引数 xNaN の場合、NaN を返します。
  • 引数 x+0 の場合、+0 を返します。
  • 引数 x-0 の場合、-0 を返します。
  • 引数 xInfinity の場合、π/2 を返します。
  • 引数 x-Infinity の場合、-π/2 を返します。

逆正接を計算するプログラム

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

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

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

このプログラムでは、Math.atan を使用して値の逆正接を計算しています。ユーザーが入力した値が 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 / 10;
const yScale = canvas.height / Math.PI;

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

for (let x = -5; x <= 5; x += 0.1) {
  const y = Math.atan(x);
  const canvasX = (x + 5) * xScale;
  const canvasY = canvas.height / 2 - y * yScale;
  ctx.lineTo(canvasX, canvasY);
}

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

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

注意点

  • 戻り値の範囲: Math.atan の戻り値は、-π/2 から π/2 の範囲です。これは、逆正接関数の主値と呼ばれます。
  • 精度: 浮動小数点演算の特性上、Math.atan の結果には微小な誤差が含まれることがあります。

脚註

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

外部リンク

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