/* calculo da integral de exp(x) entre 0 e 1 pelo met de monte carlo
 valor exato: e-1 o numero total de pontos eh NAVAL * DPONT
 usaremos a tecnica de "importance sampling"  com g(x) = 1+x */

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define NAVAL  200     /* numero de valores da integral  */
#define DPONT  100       /* apresentar resultado a cada DPONT pontos */
 /* numero aleatorio entre 0 e 1 */          
#define frand() (double)rand()/(RAND_MAX+1.)  /* excluindo valor 1 */ 
                                      
int main(){

  int i;
  double y; 
  double soma = 0.0;
  
  int np =1;
  int semente = 1400;       /* semente para o rand */
  srand(semente);
  
  while (np <= NAVAL) {
    i=0;
    while (i<DPONT) { 
      y = 3.0/2.0*frand();         /* gere um numero no intervalo 0 - 3/2 */
      soma = soma + exp(sqrt(1+2*y)-1)/sqrt(1+2*y);
      i++;
    }

    double integ = soma*1.5/(np*DPONT);     /*  a=0.0, b=1.5 */
    
    printf("%d     %f\n",np, fabs( (integ - (M_E-1.0))/(M_E-1.0) )   );
    np++;
        
  }
  return 0;
}
  
