// metropolis yöntemi ile random sayı üretir, monte darlo integrasyon // compile: gcc random.c -lm // usage: ./a.out trial# #include #include #include #include // w is gaussian weight function double w(double x, double y) { double sigma ; // sigma is standard deviation sigma = 0.05 ; return exp(-(x *x + y*y) / (2 * sigma * sigma) ) ; } void generator(double * x, double * y) { double xt, yt, ratio, tmp ; double delta = 0.2 ; tmp = (double)rand() / (double)RAND_MAX ; // update x by adding a multiples of delta , (2 * tmp - 1) creates a number between -1.0 and 1.0 xt = (*x) + delta * (2 * tmp - 1) ; tmp = (double)rand() / (double)RAND_MAX ; // update y by adding a multiples of delta , (2 * tmp - 1) creates a number between -1.0 and 1.0 yt = (*y) + delta * (2 * tmp - 1) ; // compare updated x,y values with old x,y values, accept or reject updated values as new values according to weight function ratio = w(xt, yt ) / w(*x, *y) ; tmp = (double)rand() / (double)RAND_MAX ; if(ratio > tmp ) { *x = xt ; *y = yt ; } } int main(int argc, char* argv[]) { int i; double x,y ; // how many random number will generated int count = atoi(argv[1]); //assign initial random numbers between 0-1 to x,y x = (double) rand() / RAND_MAX ; y = (double) rand() / RAND_MAX ; for(i=0 ; i < count ; i++) { printf("%f %f\n", x, y) ; generator(&x,&y); } return 0; }