javascript 配列の分散値を求める
- 作成日 2021.03.18
- 更新日 2022.08.09
- javascript
- javascript

javascriptで、配列の分散値を求めるサンプルコードを記述してます。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 104.0.5112.81
配列の分散値
配列の分散値は、数式では以下のように求めることが可能です。
(( 値 - 配列の平均値 )を2乗 )した総和 ÷ 配列の個数
実際に、平均値と分散を求めてみます。
const arr = [1, 2, 3, 4, 5]
// 平均値を計算
let sum = 0;
arr.forEach((x, i) => sum += x)
const ave = sum / arr.length;
console.log(ave); // 3
// 分散を計算
let dist = 0;
arr.forEach((x, i) => dist += (x - ave) ** 2)
console.log(dist / arr.length); // 2
サンプルコード
以下は、
「実行」ボタンをクリックすると、ランダムに生成した5個の配列の分散値を計算して表示する
サンプルコードとなります。
※cssには「tailwind」を使用してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
function hoge() {
const arr = Array(5).fill().map(x => ~~(Math.random() * 10));
// 生成した配列を表示
disp(arr, "rand");
// 平均値を計算
let sum = 0;
arr.forEach((x, i) => sum += x)
const ave = sum / arr.length;
// 分散を計算
let dist = 0;
arr.forEach((x, i) => dist += (x - ave) ** 2)
result.innerHTML = dist / arr.length;
}
//フロントに表示する関数
function disp(arr, id) {
let text = [];
// 配列を利用してfor文を作成
arr.forEach((x, i) => text.push('<li class="list-group-item">' + arr[i] + '</li>'))
//innerHTMLを使用して表示
document.getElementById(id).innerHTML = text.join('');
}
window.onload = () => {
// クリックイベントを登録
btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
}
</script>
<body>
<div class="container mx-auto my-56 w-56 px-4">
<div class="flex justify-center">
<p id="result" class="bg-teal-500 text-white py-2 px-4 rounded-full mb-3 mt-4">分散値</p>
</div>
<div class="flex justify-center">
<ul id="rand"></ul>
</div>
<div class="flex justify-center">
<button id="btn" type="button"
class="mt-5 bg-transparent border border-red-500 hover:border-red-300 text-red-500 hover:text-red-300 font-bold py-2 px-4 rounded-full">
実行
</button>
</div>
</div>
</body>
</html>
配列の分散値が計算されていることが確認できます。

-
前の記事
typescript interfaceのプロパティを追加する 2021.03.18
-
次の記事
CSS xp.cssを使ってwindows xp風のレイアウトを作成する 2021.03.18
コメントを書く