#include<stdio.h>
#include<stdio.h>
#include<math.h>
#include<gsl/gsl_errno.h>
#include<gsl/gsl_integration.h>
#include<mpi.h>

double g(double x, void *v){return exp(-x*x);}

int main(int argc,char **argv){
  int rank,nproc;
  double result,err,xmin,xmax,tol,total;
  gsl_integration_workspace *work;
  gsl_function F;

  MPI_Init(&argc,&argv);
  MPI_Comm_size(MPI_COMM_WORLD,&nproc);
  MPI_Comm_rank(MPI_COMM_WORLD,&rank);

  work=gsl_integration_workspace_alloc(100000);
  F.function=g;
  F.params=NULL;
  xmin=rank*(10.0/nproc);
  xmax=(rank+1)*(10.0/nproc);
  tol=1e-4;

  gsl_integration_qag(&F,xmin,xmax,0,tol,100000,GSL_INTEG_GAUSS15,
                      work,&total,&err);

  MPI_Reduce(&total,&result,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);

  if (rank==0)
    printf("Integral is %f\n",result);

  gsl_integration_workspace_free(work);
  MPI_Finalize();
  return(0);
}
