// weight function kullanarak monte carlo integrasyon /* COMPILATION: gcc integral1d.c -lm USAGE: ./a.out trial# This program computes integral of ( 1 / (1 + x*x) ) in x=[0,1] by using importance sampling Monte Carlo */ #include #include #include #include // f() is the function to be integrated double f(double x) { return (1.0 / (1.0 + x*x) ) ; } // random x values are generated according to probability distribution function w() double w(double x) { return ((1.0/3.0) * (4 - 2 * x)) ; } // my_rand() function generates random numbers according to p.d.f w() // this function uses inverse of the p.d.f w() double my_rand() { double y = (double)rand() / (double)RAND_MAX ; return (2.0 - sqrt(4.0 - 3.0*y) ) ; } int main(int argc, char* argv[]) { int trials; // number of random points int i; double sum = 0.0; double x; trials = atoi(argv[1]); // read number of random point from command line argument for(i=0 ; i < trials ; i++ ) { x = my_rand() ; sum += ( f(x) / w(x)) ; } double integral = sum / trials ; printf("computed value of the integral= %f \n", integral); printf("true value of the integral= %f \n", atan(1.0)); printf("error= %f \n", fabs( integral - atan(1.0))); return 0; }