【问题标题】:Calculating the integrals using MC method使用 MC 方法计算积分
【发布时间】:2017-05-28 19:14:22
【问题描述】:

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

【问题讨论】:

  • 为什么不做黎曼和?
  • 与您的问题无关,但您不需要乘以 -1 以使数字变为负数。在 C++ 中,否定运算符是可用于任何表达式的一元运算符。例如,如果您有一个变量或表达式e,只需使用一元减号使其为负数,如-e

标签: c++ integral


【解决方案1】:

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

应该是

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

你把边界推得太远了。

【讨论】:

    【解决方案2】:

    您正在将pickPoint(leftBorder, rightBorder) 添加到leftBorder。您已经获得了介于 leftBorderrightBorder 之间的值。没有必要添加。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-02
      • 2021-06-19
      • 2016-11-15
      相关资源
      最近更新 更多