#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define NUM_POINTS 1000000
#define TRUE_AREA (M_PI - 3 * sqrt(3) + 3) / 3
#define NUM_STEPS 12
int is_inside(double x, double y) {
double r = 1.0;
if ((x - 0) * (x - 0) + (y - 1) * (y - 1) <= r * r &&
(x - 1) * (x - 1) + (y - 0) * (y - 0) <= r * r &&
(x - 0) * (x - 0) + (y - 0) * (y - 0) <= r * r &&
(x - 1) * (x - 1) + (y - 1) * (y - 1) <= r * r) {
return 1;
}
return 0;
}
int main() {
int i, inside_count = 0;
double x, y;
double estimated_area;
double error;
int step_size = NUM_POINTS / NUM_STEPS;
for (i = 1; i <= NUM_POINTS; i++) {
x
= (double)rand() / RAND_MAX
; y
= (double)rand() / RAND_MAX
;
if (is_inside(x, y)) {
inside_count++;
}
if (i % step_size == 0) {
estimated_area = 4.0 * (double)inside_count / i;
error
= fabs(estimated_area
- TRUE_AREA
);
}
}
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4KI2luY2x1ZGUgPG1hdGguaD4KI2luY2x1ZGUgPHRpbWUuaD4KCiNkZWZpbmUgTlVNX1BPSU5UUyAxMDAwMDAwCiNkZWZpbmUgVFJVRV9BUkVBIChNX1BJIC0gMyAqIHNxcnQoMykgKyAzKSAvIDMKI2RlZmluZSBOVU1fU1RFUFMgMTIKCmludCBpc19pbnNpZGUoZG91YmxlIHgsIGRvdWJsZSB5KSB7CiAgICBkb3VibGUgciA9IDEuMDsKICAgIGlmICgoeCAtIDApICogKHggLSAwKSArICh5IC0gMSkgKiAoeSAtIDEpIDw9IHIgKiByICYmICAKICAgICAgICAoeCAtIDEpICogKHggLSAxKSArICh5IC0gMCkgKiAoeSAtIDApIDw9IHIgKiByICYmICAKICAgICAgICAoeCAtIDApICogKHggLSAwKSArICh5IC0gMCkgKiAoeSAtIDApIDw9IHIgKiByICYmICAKICAgICAgICAoeCAtIDEpICogKHggLSAxKSArICh5IC0gMSkgKiAoeSAtIDEpIDw9IHIgKiByKSB7ICAKICAgICAgICByZXR1cm4gMTsKICAgIH0KICAgIHJldHVybiAwOwp9CgppbnQgbWFpbigpIHsKICAgIGludCBpLCBpbnNpZGVfY291bnQgPSAwOwogICAgZG91YmxlIHgsIHk7CiAgICBkb3VibGUgZXN0aW1hdGVkX2FyZWE7CiAgICBkb3VibGUgZXJyb3I7CiAgICBpbnQgc3RlcF9zaXplID0gTlVNX1BPSU5UUyAvIE5VTV9TVEVQUzsKCiAgICBzcmFuZCh0aW1lKE5VTEwpKTsKCiAgICBwcmludGYoIuS5seaVsOOBruWAi+aVsCwg6Kqk5beuXG4iKTsKCiAgICBmb3IgKGkgPSAxOyBpIDw9IE5VTV9QT0lOVFM7IGkrKykgewogICAgICAgIHggPSAoZG91YmxlKXJhbmQoKSAvIFJBTkRfTUFYOwogICAgICAgIHkgPSAoZG91YmxlKXJhbmQoKSAvIFJBTkRfTUFYOwoKICAgICAgICBpZiAoaXNfaW5zaWRlKHgsIHkpKSB7CiAgICAgICAgICAgIGluc2lkZV9jb3VudCsrOwogICAgICAgIH0KCiAgICAgICAgaWYgKGkgJSBzdGVwX3NpemUgPT0gMCkgewogICAgICAgICAgICBlc3RpbWF0ZWRfYXJlYSA9IDQuMCAqIChkb3VibGUpaW5zaWRlX2NvdW50IC8gaTsKICAgICAgICAgICAgZXJyb3IgPSBmYWJzKGVzdGltYXRlZF9hcmVhIC0gVFJVRV9BUkVBKTsKCiAgICAgICAgICAgIHByaW50ZigiJWQsJWZcbiIsIGksIGVycm9yKTsKICAgICAgICB9CiAgICB9CgogICAgcHJpbnRmKCLoqIjnrpfjgYzlrozkuobjgZfjgb7jgZfjgZ/jgIJcbiIpOwoKICAgIHJldHVybiAwOwp9Cg==
乱数の個数, 誤差
83333,0.945194
166666,0.942674
249999,0.942570
333332,0.939170
416665,0.938993
499998,0.941210
583331,0.942115
666664,0.943004
749997,0.943968
833330,0.945170
916663,0.945369
999996,0.945498
計算が完了しました。