使用 MC 方法计算积分

Calculating the integrals using MC method

我正在尝试编写一种算法,使用 Monte Carlo 方法求解积分。然而对于给定的输入数据,计算结果与预期不同;我计算表达式 exp(-ax^2), a = 1 并且点在 [0.5, 1] 范围内。我期望得到的结果大约是 0.29,但我得到的结果是 0.11。也许有什么建议我做错了什么?

#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)));
}

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

应该是

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

你把边界推得太远了。

您正在将 pickPoint(leftBorder, rightBorder) 添加到 leftBorder。您已经获得 leftBorderrightBorder 之间的值。不需要添加。