-
Notifications
You must be signed in to change notification settings - Fork 0
/
DrawGraph.ts
132 lines (115 loc) · 3.81 KB
/
DrawGraph.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
class GraphDrawer {
chart: Chart;
sumCount: number = 0;
plotTimerId: number;
updateTimerId: number;
probability: number;
// グラフの初期化
InitializeGraph(_reciprocalOfProb: number, _contextId: string) {
const ctx: any = document.getElementById(_contextId);
const data = {
datasets: [{
radius: 0,
label: "期待値",
data: [],
showLine: true,
fill: false,
borderColor: 'rgb(255, 99, 132)',
backgroundColor: 'rgb(255, 99, 132)',
}, {
radius: 0,
label: "試行回数の平均",
data: [],
showLine: true,
fill: false,
borderColor: 'rgb(99, 255, 132)',
backgroundColor: 'rgb(99, 255, 132)',
}, {
radius: 0,
label: "1回の試行回数",
data: [],
showLine: true,
fill: false,
borderColor: 'rgb(132, 99, 255)',
backgroundColor: 'rgb(132, 99, 255)',
steppedLine: <'middle'>"middle",
borderWidth: 1,
}],
};
var config = {
animation: {
duration: 1
},
scales: {
xAxes: [{
ticks: {
min: 1,
}
}],
yAxes: [{
ticks: {
min: 1,
max: _reciprocalOfProb * 2,
}
}],
},
tooltips: {
enabled: false,
},
legend: {
position: <'bottom'>'bottom'
},
events: [],
};
var plugins = {
type: 'scatter',
data: data,
options: config
};
this.chart = new Chart(ctx, plugins);
this.probability = 1 / _reciprocalOfProb;
}
// シミュレーションをしてグラフに値をプロットする
public Plot(_reciprocalOfProb: number, _interval: number): void {
this.plotTimerId = setInterval(() => {
this.AppendPlot();
}, _interval);
this.updateTimerId = setInterval(() => {
this.chart.update();
}, 10);
}
// グラフの描画を停止する
public Stop(): void {
clearInterval(this.plotTimerId);
clearInterval(this.updateTimerId);
}
// 一回分シミュレーションしてその結果をグラフに設定する
private AppendPlot(): void {
if (!this.chart.data.datasets) {
this.chart.data.datasets = [];
}
if (!this.chart.data.datasets[0].data) {
this.chart.data.datasets[0].data = [];
}
var plotNum: number = this.chart.data.datasets[0].data.length + 1;
var tryCount: number = this.TryOnece();
this.sumCount += tryCount;
(this.chart.data.datasets[0].data as {}[]).push({ x: plotNum, y: 1 / this.probability });
(this.chart.data.datasets[1].data as {}[]).push({ x: plotNum, y: this.sumCount / plotNum });
(this.chart.data.datasets[2].data as {}[]).push({ x: plotNum, y: tryCount });
const expectationElem = document.getElementById('averageTryCount');
if (expectationElem)
expectationElem.innerText = (this.sumCount / plotNum).toFixed(2);
}
// 1/Xが1回当たるまで繰り返す試行を一回を行う
private TryOnece(): number {
var count: number = 0;
while (true) {
count++;
if (Math.random() <= this.probability) {
break;
}
}
return count;
}
}