粒子フィルタを調べていたら、モンテカルロ法なるものが出てきました。そこで、基本の勉強にと円周率(pi = 3.1415...)をJavascriptで近似してみました。
コード
pi.js
const points = process.argv[2];
let innerPoints = 0;
for (var i = 0; i < points; i++) {
const point = { x: Math.random(), y: Math.random() };
const distance = Math.sqrt(Math.pow(point.x, 2) + Math.pow(point.y, 2));
if (distance < 1) innerPoints +=1;
}
const probability = innerPoints / points;
console.log(`pi = ${4 * probability}`);
実験
サンプル数 : 1000
$ node pi.js 1000
pi = 3.072
サンプル数 : 10000
$ node pi.js 10000
pi = 3.1312
サンプル数 : 100000
$ node pi.js 100000
pi = 3.14572
サンプル数 : 1000000
$ node pi.js 1000000
pi = 3.144628
サンプル数 : 10000000
$ node pi.js 10000000
pi = 3.1401728
サンプル数 : 100000000
$ node pi.js 100000000
pi = 3.14142492
結論と思い出
当たり前のことですが、サンプル数を増やすと円周率の近似精度が高くなることが分かります。ところで関係のない話ですが、小学生のころに塾で円周率を暗記する遊びが流行っていたのを思い出しました。今やっとその暗記の努力が日の目をみたように思います。円周率の近似精度が高くなっているのが一目でわかるので。今はpi: 3.14159265358979323846264338...
と26桁まで思い出すことができました。