-
Notifications
You must be signed in to change notification settings - Fork 0
/
getPI.html
109 lines (104 loc) · 3.32 KB
/
getPI.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>statisticalMechanicsOfMoney</title>
</head>
<body>
<canvas id="canvas1" style="background:gainsboro;" width="600" height="600"></canvas>
<script>
let montaCarloPiData = {
// 投放上限
total: 359000,
// 总投放数量
count: 0,
// 圆内数量
sum: 0,
// 每次投放点数
points: 1000,
//保存生成的不重复的随机x,y坐标
dict: {},
};
// 求PI
function run(id) {
let canvas = document.getElementById(id);
if (!canvas) {
return false;
}
// 获取上下文对象
let context = canvas.getContext('2d');
// 设置颜色
context.fillStyle = 'blue';
setInterval(function () {
if (montaCarloPiData.count < montaCarloPiData.total) {
montaCarloPiData.count += montaCarloPiData.points;
montaCarloPiData.sum = montaCarloPiData.sum + addPoints(montaCarloPiData.dict, canvas.getAttribute('width'), montaCarloPiData.points);
draw(context, montaCarloPiData.dict);
// 求PI
console.log(montaCarloPiData.sum / montaCarloPiData.count * 4);
}
}, 2000);
}
// 生成指定数量的点
function addPoints(dict, max, size, sum = 0) {
// 获取圆心x y
let centerX = max / 2;
let centerY = max / 2;
let count = 0;
for (let i = 0; i < size; i++) {
let x = Math.floor(Math.random() * max);
let y = Math.floor(Math.random() * max);
if (!isNaN(x) && !isNaN(y)) {
let xKey = x.toString();
let yKey = y.toString();
let yDict = dict[xKey];
if (yDict) {
if (!yDict[yKey]) {
dict[xKey][yKey] = '1';
count += 1;
sum = countPoints(x, y, centerX, centerY, max, sum);
}
} else {
dict[xKey] = {};
dict[xKey][yKey] = '1';
count += 1;
sum = countPoints(x, y, centerX, centerY, max, sum);
}
}
}
if (count < size) {
return addPoints(dict, max, size - count, sum);
}
return sum;
}
// 校验,点如果投在圆内,则sum+1
function countPoints(x, y, centerX, centerY, max, sum) {
let distance = countDistance(x, y, centerX, centerY);
if (distance <= max / 2) {
// 点在圆内,计数
sum += 1;
}
return sum;
}
// 计算两点距离
function countDistance(x, y, centerX, centerY) {
let dx = Math.abs(x - centerX);
let dy = Math.abs(y - centerY);
return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
// 画点
function draw(context, dict) {
// 清空画布
// context.clearRect(0, 0, 1500, 800);
context.fillStyle = 'blue';
// fillRect:填充矩形,指定坐标x,y,宽高
for (let x in dict) {
for (let y in dict[x]) {
context.fillRect(parseInt(x), parseInt(y), 1, 1);
}
}
}
run('canvas1');
</script>
</body>
</html>