Search code examples
c++integral

Calculating the integrals using MC method


I'm trying to write an algorithm that will solve integrals using the Monte Carlo method. Nevertheless for a given input data, the calculation result is different from the expected one; I calculate expression exp(-ax^2), a = 1 and points are in range of [0.5, 1]. The result I expected to get is about 0.29 but I got something like 0.11. Maybe any suggestions what am I doing wrong?

#include<iostream>
#define N 100000000
#include<ctime>
#include<cmath>
#include<cstdio>
#include<cstdlib>

double pickPoint(double left, double right);
double functionE(double a, double x);

int main(){
  srand(time(NULL));
  double a;
  std::cin >> a;
  double leftBorder, rightBorder;
  std::cin >> leftBorder >> rightBorder;
  double result = 0;
  for (int j = 0; j < N; j++){
        result += functionE(a, leftBorder + pickPoint(leftBorder, rightBorder));
  }
  printf("%lf", (rightBorder - leftBorder) * (result / N));
  return 0;
}

double pickPoint(double left, double right){
  return left + (double)(rand() / (RAND_MAX + 1.0) * (right - left));
}

double functionE(double a, double x){
  return exp((-a*pow(x, 2)));
}

Solution

  • result += functionE(a, leftBorder + pickPoint(leftBorder, rightBorder));

    should be

    result += functionE(a, pickPoint(leftBorder, rightBorder));

    You pushed the border to far off.