#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define M_PI 3.14159265
int main() {
double a, b, s, x1, x2, y1, y2;
double r, q1, q2, shinchi;
int count, m, n;
// 理論的な重複領域の面積
shinchi = M_PI / 2.0 - 1.0;
// 円の中心と半径の設定
x1 = 1.0; y1 = 0.0;
x2 = 0.0; y2 = 1.0;
r = 1.0;
// 各乱数の個数についてモンテカルロ法を実行
for (n = 10; n <= 100000; n = n * 5) {
count = 0;
s = 0.0;
for (m = 0; m < n; m++) {
a
= (double)rand() / RAND_MAX
; b
= (double)rand() / RAND_MAX
; q1 = (a - x1) * (a - x1) + (b - y1) * (b - y1);
q2 = (a - x2) * (a - x2) + (b - y2) * (b - y2);
if (q1 < r * r && q2 < r * r) {
s += 1.0;
}
count++;
}
s = s / count;
s = s * 4; // 単位正方形内の割合から全体の面積に換算
printf("乱数の個数: %d, 誤差: %f\n", n
, fabs(s
- shinchi
)); }
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPG1hdGguaD4KI2RlZmluZSBNX1BJIDMuMTQxNTkyNjUKCmludCBtYWluKCkgewogICAgZG91YmxlIGEsIGIsIHMsIHgxLCB4MiwgeTEsIHkyOwogICAgZG91YmxlIHIsIHExLCBxMiwgc2hpbmNoaTsKICAgIGludCBjb3VudCwgbSwgbjsKCiAgICAvLyDnkIboq5bnmoTjgarph43opIfpoJjln5/jga7pnaLnqY0KICAgIHNoaW5jaGkgPSBNX1BJIC8gMi4wIC0gMS4wOwoKICAgIC8vIOWGhuOBruS4reW/g+OBqOWNiuW+hOOBruioreWumgogICAgeDEgPSAxLjA7IHkxID0gMC4wOwogICAgeDIgPSAwLjA7IHkyID0gMS4wOwogICAgciA9IDEuMDsKCiAgICAvLyDlkITkubHmlbDjga7lgIvmlbDjgavjgaTjgYTjgabjg6Ljg7Pjg4bjgqvjg6vjg63ms5XjgpLlrp/ooYwKICAgIGZvciAobiA9IDEwOyBuIDw9IDEwMDAwMDsgbiA9IG4gKiA1KSB7CiAgICAgICAgY291bnQgPSAwOwogICAgICAgIHMgPSAwLjA7CiAgICAgICAgZm9yIChtID0gMDsgbSA8IG47IG0rKykgewogICAgICAgICAgICBhID0gKGRvdWJsZSlyYW5kKCkgLyBSQU5EX01BWDsKICAgICAgICAgICAgYiA9IChkb3VibGUpcmFuZCgpIC8gUkFORF9NQVg7CiAgICAgICAgICAgIHExID0gKGEgLSB4MSkgKiAoYSAtIHgxKSArIChiIC0geTEpICogKGIgLSB5MSk7CiAgICAgICAgICAgIHEyID0gKGEgLSB4MikgKiAoYSAtIHgyKSArIChiIC0geTIpICogKGIgLSB5Mik7CiAgICAgICAgICAgIGlmIChxMSA8IHIgKiByICYmIHEyIDwgciAqIHIpIHsKICAgICAgICAgICAgICAgIHMgKz0gMS4wOwogICAgICAgICAgICB9CiAgICAgICAgICAgIGNvdW50Kys7CiAgICAgICAgfQogICAgICAgIHMgPSBzIC8gY291bnQ7CiAgICAgICAgcyA9IHMgKiA0OyAgLy8g5Y2Y5L2N5q2j5pa55b2i5YaF44Gu5Ymy5ZCI44GL44KJ5YWo5L2T44Gu6Z2i56mN44Gr5o+b566XCiAgICAgICAgcHJpbnRmKCLkubHmlbDjga7lgIvmlbA6ICVkLCDoqqTlt646ICVmXG4iLCBuLCBmYWJzKHMgLSBzaGluY2hpKSk7CiAgICB9CgogICAgcmV0dXJuIDA7Cn0K