使用 MC 方法计算积分

Calculating the integrals using MC method

本文关键字:计算 方法 MC 使用      更新时间:2023-10-16

我正在尝试编写一种算法,该算法将使用蒙特卡洛方法解决积分。然而,对于给定的输入数据,计算结果与预期结果不同;我计算表达式 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));

你把边界推得很远。

您正在向leftBorder添加pickPoint(leftBorder, rightBorder)。您已经获得了一个介于 leftBorderrightBorder 之间的值。这种添加是不必要的。