モンテカルロ in tegration のコードを c++ で作成しました。これは、2 次元積分を使用したときに他の関数でうまく機能しました。N 次元積分のコードを一般化しました。この特定のケースでは、n = 10 を使用しています。単純な関数 f = x1+x2+x3+x4+x5+....+x10 を積分しようとしています。 ...x10 は制限 [-5.0, 5.0] 内にあります。絶対結果が 0 であることを知っているのに、結果に大きな偏差が見られます。誰か親切に私のコードを見て、私のコードがどこで壊れているかを見つけていただければ幸いです。次のようにコードを添付しています。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
//define multivariate function F(x1, x2, ...xk)
double f(double x[], int n)
{
double y;
int j;
y = 0.0;
for (j = 0; j < n; j = j+1)
{
y = y + x[j];
}
y = y;
return y;
}
/*
* Function f(x1, x2, ... xk)
*/
//define function for Monte Carlo Multidimensional integration
double int_mcnd(double(*fn)(double[],int),double a[], double b[], int n, int m)
{
double r, x[n], p;
int i, j;
// initial seed value (use system time)
srand(time(NULL));
r = 0.0;
p = 1.0;
// step 1: calculate the common factor p
for (j = 0; j < n; j = j+1)
{
p = p*(b[j]-a[j]);
}
// step 2: integration
for (i = 1; i <= m; i=i+1)
{
// calculate random x[] points
for (j = 0; j < n; j = j+1)
{
x[j] = a[j] + static_cast <double> (rand()) /( static_cast <double> (RAND_MAX/(b[j]-a[j])));
}
r = r + fn(x,n);
}
r = r*p/m;
return r;
}
double f(double[], int);
double int_mcnd(double(*)(double[],int), double[], double[], int, int);
int main(int argc, char **argv)
{
/* define how many integrals */
const int n = 10;
double b[n] = {5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0,5.0};
double a[n] = {-5.0, -5.0, -5.0, -5.0, -5.0, -5.0, -5.0, -5.0, -5.0,-5.0};
double result;
int i, m;
int N = 20;
cout.precision(6);
cout.setf(ios::fixed | ios::showpoint);
// current time in seconds (begin calculations)
time_t seconds_i;
seconds_i = time (NULL);
m = 2; // initial number of intervals
// convert command-line input to N = number of points
//N = atoi( argv[1] );
for (i=0; i <=N; i=i+1)
{
result = int_mcnd(f, a, b, n, m);
cout << setw(30) << m << setw(30) << result <<endl;
m = m*2;
}
// current time in seconds (end of calculations)
time_t seconds_f;
seconds_f = time (NULL);
cout << endl << "total elapsed time = " << seconds_f - seconds_i << " seconds" << endl << endl;
return 0;
}
私が得ている出力は次のようなものです:
4 -41046426010.339691
8 -14557222958.913620
16 25601187040.145161
32 29498213233.367203
64 -2422980618.248888
128 -13400105151.286720
256 -11237568021.855265
512 -5950177645.396674
1024 -4726707072.013641
2048 -1240029475.829825
4096 1890210492.995555
8192 573067706.448856
16384 356227781.143659
32768 -343198855.224271
65536 171823353.999405
131072 -143383711.461758
262144 -197599063.607231
524288 -59641584.846697
1048576 10130826.266767
2097152 100880200.681037
total elapsed time = 1 seconds
これは、予想される出力ゼロに近いものではありません。コードの修正を手伝ってください。事前に感謝します。