javascript 引数を全て2乗した総和の平方根を計算する

javascript 引数を全て2乗した総和の平方根を計算する

javascriptでmathオブジェクトのhypotメソッドを使用して引数を全て2乗した総和の平方根を計算するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 102.0.5005.63

hypotメソッド使い方

「hypot」メソッドを使うと引数を全て2乗した総和の平方根の計算を行うことが可能です。

数値を2つにすると、直角三角形の斜辺の長さを計算するのにも利用できます。

Math.hypo(数値,数値,数値.....,数値)

「hypot」メソッド使い方

console.log(Math.hypot(1,2)); 
// 結果 2.23606797749979

console.log(Math.hypot(1,Math.sqrt(3))); // Math.sqrt(3) → ルート 3
// 結果 2

console.log(Math.hypot(3,4));
// 結果 5

console.log(Math.hypot(5,12));
// 結果 13

console.log(Math.hypot(8,15));
// 結果 17

console.log(Math.hypot(1.1,1.2));
// 結果 1.6278820596099706

console.log(Math.hypot(1,1,1,2,3)); // 1 + 1 + 1 + 4 + 9の平方根
// 結果 4

サンプルコード

以下は、テキストフォームに入力した2つの数値を2乗した総和の平方根を 、 別のテキストフォームに出力するだけのサンプルコードとなります。

※cssには「uikit」を使用してます。

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

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- UIkit CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/css/uikit.min.css" />

  <!-- UIkit JS -->
  <script src="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/js/uikit.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/uikit@3.5.5/dist/js/uikit-icons.min.js"></script>
</head>
<style>
  .main {
    margin: 0 auto;
    margin-top: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 20px;
  }
</style>
<script>

  function cal() {

    //テキストボックスの値を取得
    let val1 = document.getElementsByName("text-box")[0].value;
    let val2 = document.getElementsByName("text-box2")[0].value;
    
    //立方根の値を計算して表示
    document.getElementsByClassName("text-box-class")[0].value = Math.hypot(val1, val2);

  }

</script>

<body>
  <div class="main">
    <div class="uk-light uk-background-secondary uk-padding">

      <form>
        <fieldset class="uk-fieldset">
          <legend class="uk-legend">平方根</legend>
          <div class="uk-margin">
            <input id="text-box3" name="text-box3" class="uk-input text-box-class" type="text" placeholder="Input">
          </div>
        </fieldset>
      </form>

      <form>
        <fieldset class="uk-fieldset">
          <legend class="uk-legend">値1</legend>
          <div class="uk-margin">
            <input id="text-box" name="text-box" class="uk-input" type="number" placeholder="Input">
          </div>
        </fieldset>
      </form>

      <form>
        <fieldset class="uk-fieldset">
          <legend class="uk-legend">値2</legend>
          <div class="uk-margin">
            <input id="text-box2" name="text-box2" class="uk-input" type="number" placeholder="Input">
          </div>
        </fieldset>
      </form>

      <p uk-margin>
        <button class="uk-button uk-button-danger" onclick="cal()">計算</button>
      </p>

    </div>
  </div>
</body>

</html>

平方根の値が計算されて出力されていることが確認できます。