とりあえず、正規分布配列の検証(2)で作った正規分布配列を、前回作成したヒストグラムのコードに追加。
グラフの初期値を-10、終わりを10、データ間隔を0.1に設定
xbins: {
end: 10,
size: 0.1,
start: -100,
},
全体のコードは以下の通り
<!DOCTYPE html>
<html>
<head>
<!-- Load plotly.js into the DOM -->
<script src="https://cdn.plot.ly/plotly-2.27.0.min.js"></script>
</head>
<body>
<div id="myDiv"><!-- Plotly chart will be drawn inside this DIV --></div>
<p>データの個数:<span id="pieces"></span></p>
<p>合計:<span id="sum"></span></p>
<p>平均:<span id="average"></span></p>
<p>分散:<span id="variance"></span></p>
<p>標準偏差σ:<span id="sd"></span></p>
<script>
const nd = [];
function getRandomValue() {
var x, y, z;
for (let i = 0; i < 100000; i++) {
x = Math.random();
y = Math.random();
z = Math.sqrt(-2 * Math.log(x)) * Math.cos(2 * Math.PI * y);
nd.push(z);
}
}
// getRandomValue()を呼び出して100,000回発生させる
getRandomValue();
// データの個数を表示
document.getElementById("pieces").textContent = nd.length;
// データの合計を求める
const sum = nd.reduce((a, b) => a + b, 0);
document.getElementById("sum").textContent = sum;
// データの平均を求める
const average = sum / nd.length;
document.getElementById("average").textContent = average;
// データの分散を求める
const sumSquaredDiff = nd.reduce((a, b) => a + (b - average) ** 2, 0);
const variance = sumSquaredDiff / nd.length;
document.getElementById("variance").textContent = variance;
// データの標準偏差を求める
const standardDeviation = Math.sqrt(variance);
document.getElementById("sd").textContent = standardDeviation;
var trace = {
x: nd,
autobinx: false,
marker: {
color: "blue",
line: {
color: "white",
width: 0,
},
},
type: "histogram",
xbins: {
end: 10,
size: 0.1,
start: -100,
},
};
var data = [trace];
var layout = {
bargap: 0.05,
bargroupgap: 0.2,
title: "Sampled Results",
xaxis: { title: "Value" },
yaxis: { title: "Count" },
};
Plotly.newPlot("myDiv", data, layout);
</script>
</body>
</html>
結果
データの個数:
合計:
平均:
分散:
標準偏差σ:
正規分布
コメント