確率・統計の教科書でおなじみの「千鳥足」のシミュレートを行う。ここでは主に関数の説明を行う。
ルールは 0 〜 1 までの疑似乱数を振って
| 0 以上 0.25 未満 | |
| 0.25 以上 0.5 未満 | |
| 0.5 以上 0.75 未満 | |
| 0.75 以上 1 以下 |
の様に進むことにする5。そして、自分の家(
)に到着した時点
で終了とし、それまでの経路、および歩数をファイルに出力する。ただし、ここ
では簡単のため、シェルのリダイレクト ''>'' を用いて出力ファイル out.dat に出力する。
プログラムはそんなに複雑なものではないが、ここでは
random_walk.c --------------------------------------------------------
#include"random_walk.h"
int main(){
int x = 0, y = 0, i = 0;
double Prw;
do{
printf("(x, y) = (%d, %d) \n",x,y);
Prw = ran();
if(Prw < 0.25) x--;
else if((Prw >= 0.25) && (Prw < 0.5)) y--;
else if((Prw >= 0.5) && (Prw < 0.75)) x++;
else y++;
i++;
}while((x != XHOME) || (y != YHOME));
printf("(x, y) = (%d, %d) \n",x,y);
printf("無事に家に着きました。%d 歩 \n", i);
}
ran.c ----------------------------------------------------------------
#define IA 7141
#define IC 54773
#define IM 259200
double ran(){
static long iseed=12354;
iseed = (iseed*IA+IC)%IM;
return (double)iseed/(double)IM;
}
random_walk.h --------------------------------------------------------
#define XHOME 10
#define YHOME 10
double ran();
実行結果 -------------------------------------------------------------
s1:~/c_text> ./random_walk > out.dat
s1:~/c_text> cat out.dat
0, 0
0, -1
0, 0
…
9, 10
10, 10
無事に家に着きました。9922 歩
s1:~/c_text> gnuplot
gnuplot> plot"out.dat" u 1:2