// kadai1-2.cpp
// ex) plot "???.txt" w boxes
#define _USE_MATH_DEFINES
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//ランダムウォークのステップ数
const int STEPS = 1000;
const int RANDOMS = 1000; //生成する乱数の個数
const int LOWER_LIMIT = 0; //ヒストグラムの下限と
const int UPPER_LIMIT = 99; //上限
const int DIVISION = 1; //分割数(1の幅をDIVISION等分)
//0以上1未満の一様乱数を生成する
double frand()
{
return rand() / (RAND_MAX+1.0);
}
//Box-Muller法で標準正規乱数を生成する
double box_muller()
{
//Box-Muller法は2個の一様乱数から2個の正規乱数を生成する
//そのうち一方はすぐに返し、もう一方は次に呼び出されたときに返す
static bool haveRandom = false;
static double random;
if(haveRandom){
//正規乱数はすでにできている
haveRandom = false;
return random;
} else {
//正規乱数は手元にないので新しく2個の正規乱数を作る
double u1 = sqrt(-2*log(1-frand()));
double u2 = 2*M_PI*frand();
//2個のうち一方は次の呼び出しのためにとっておく
haveRandom = true;
random = u1 * sin(u2);
//もう一方を返す
return u1 * cos(u2);
}
}
int main()
{
double x, y, d;
int i, step, h;
//乱数を初期化する
srand((unsigned int)time(NULL));
//頻度を記録する配列、0で初期化
int hist[(UPPER_LIMIT - LOWER_LIMIT) * DIVISION + 1] = {0};
for (i = 0; i < RANDOMS; i++) {
//STEPSステップのランダムウォークを実施する
x = y = 0.0;
for (step = 0; step < STEPS; step++) {
x += box_muller();
y += box_muller();
}
d = sqrt(x * x + y * y);
h = (int)d;
if (h <= UPPER_LIMIT) {
hist[h]++;
}
}
for (h = LOWER_LIMIT; h <= UPPER_LIMIT; h++) {
printf("%3d %d\n", h, hist[h]);
}
return 0;
}
Ly8ga2FkYWkxLTIuY3BwCi8vIGV4KSBwbG90ICI/Pz8udHh0IiB3IGJveGVzCiNkZWZpbmUgX1VTRV9NQVRIX0RFRklORVMKI2luY2x1ZGUgPG1hdGguaD4KI2luY2x1ZGUgPHN0ZGlvLmg+CiNpbmNsdWRlIDxzdGRsaWIuaD4K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