javascript 三角関数acos(アークコサイン)の値を計算する

javascript 三角関数acos(アークコサイン)の値を計算する

javascriptでmathオブジェクトのacosメソッドを使用して三角関数acos(アークコサイン)の値を計算するサンプルコードを記述してます。

環境

  • OS windows11 home
  • Apache 2.4.43
  • ブラウザ chrome 105.0.5195.127

acosメソッド使い方

acosメソッドを使うと三角関数acos(アークコサイン)の計算を行うことが可能です。

Math.acos(ラジアン単位の角度)

角度の単位はラジアンなので、30度は

(30/360)*(2*Math.PI)で

30 * (Math.PI / 180)となります。

Math.PIは円周率(π)を返してくれます

acosメソッド使い方

console.log( Math.acos(15 * (Math.PI / 180)) );
// 結果 0.1.3059101797706607

console.log( Math.acos(30 * (Math.PI / 180)) );
// 結果 1.0197267436954502

サンプルコード

以下は、テキストフォームに入力した数値(ラジアン値)のacos(アークコサイン)の値を計算して出力するだけのサンプルコードとなります。

※cssには「tailwind」を使用してます。関数はアロー関数を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
</head>

<script>

  window.onload = () => {

    btn.onclick = () => {
      foo.innerHTML = Math.acos(Number(txt.value) * (Math.PI / 180))
    }

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <h1 class="font-semibold text-blue-500 text-lg mr-auto">実行結果</h1>

      <p id="foo" class="font-semibold text-lg mr-auto"></p>

      <input
        class="mb-2 shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
        id="txt" type="text">

      <button id="btn"
        class="mb-2 md:mb-0 bg-transparent hover:bg-yellow-500 text-yellow-700 font-semibold hover:text-white py-2 px-4 border border-yellow-500 hover:border-transparent rounded">
        実行
      </button>

    </div>

  </div>
</body>

</html>

acos(アークコサイン)の値が計算されて出力されていることが確認できます。