我写了一个程序,用蒙特卡罗方法计算函数(比如sin(x))的定积分。但是,我认为我使用mt19937的方式是不正确的,或者代码中存在另一个问题,因为它没有返回预期的结果。
下面是我的代码:
mt19937 RandomEngine(0);
uniform_real_distribution<double> RandomDouble(0.0,1.0);
double x = RandomDouble(RandomEngine);
int NumberOfSimulations;
cin >> NumberOfSimulations;
double SumOfValues=0;
for (int iSimulation = 0; iSimulation < (NumberOfSimulations -1 ); iSimulation++)
{
SumOfValues += sin(x);
}
SumOfValues /= NumberOfSimulations;
cout << "The integral's result is: " << SumOfValues << endl;
你能告诉我为什么输出连你都不准确吗?
您的程序在double x=RandomDouble(随机引擎);
中获取一个随机样本,然后重复地添加它的正弦。
您需要在每次迭代中抽取一个随机样本。将double x=RandomDouble(随机引擎);
移动到循环中。
此外,(int iSimulation=0;iSimulation<(NumberOfSimulations-1);iSimulation++)的似乎使用了错误的界限。对
NumberOfSimulations-1
样本求和,然后除以NumberOfSimulations
。