使用MC方法计算积分

时间:2017-05-28 19:14:23

标签: c++ integral

我试图编写一种能够使用蒙特卡罗方法求解积分的算法。然而,对于给定的输入数据,计算结果与预期的不同;我计算表达式 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)));
}

2 个答案:

答案 0 :(得分:1)

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

应该是

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

你把边界推到了很远的地方。

答案 1 :(得分:0)

您要将if(imagevew.getImage()==R.drawable.image1){ //do some stuff } 添加到pickPoint(leftBorder, rightBorder)。您已获得leftBorderleftBorder之间的值。这种补充是没有必要的。