所以,我在这里遇到一个小问题,因为 for 循环相当大。这个程序是模拟每步 100 步的随机游走 - 我想做的是让程序执行 100 万次这样的随机游走模拟(随机游走是通过嵌套的 for 循环基本上通过模拟翻转硬币来完成的,如下所示您可以在下面的代码中看到)并从每个随机游走中获取所得位移并将其打印到控制台窗口和指定的输出文件。
但是,我的代码似乎是从嵌套的 for 循环中添加 x 的每个最终值,然后将它们打印到控制台窗口(并保存到输出文件) - 我不想要这个,我只想要独立的网络每个 j 值(其范围从 1 到 1E6,由外部 for 循环指定)输出的每次随机游走的结果。
因此,任何帮助将不胜感激。另外,我非常感谢您不仅引用一些代码供我使用,而是向我解释我的程序逻辑出了问题以及原因。
提前致谢,我的代码如下!
#include <iostream>
#include <ctime>
#include <fstream>
using namespace std;
int main(void) {
const unsigned IM = 1664525;
const unsigned IC = 1013904223;
const double zscale = 1.0/0xFFFFFFFF; //Scaling factor for random double between 0 and 1
unsigned iran = time(0); //Seeds the random-number generator from the system time
const int nsteps(100); //Number of steps
const int nwalks(1E6);
int x(0); // Variable to count step forward/back
ofstream randout;
randout.open("randomwalkdata2.txt");
// Table headers for console window and output file
cout << "Random Walk Number \t Resultant Displacement \n";
randout << "Random Walk Number \t Resultant Displacement \n";
for ( int j = 1 ; j <= nwalks ; j++ ) {
for ( int i = 1 ; i <= nsteps ; i++ ) {
// if-else statement to increment/decrement x based on RNG
if ( zscale * double( iran = IM * iran + IC ) < 0.5 ) //RNG algorithm
x++;
else
x--;
}
cout << j << "\t" << x << endl;
randout << j << "\t" << x << endl;
}
randout.close();
return 1;
}
最佳答案
您忘记在每次随机游走后重新初始化 x。
cout << j << "\t" << x << endl;
randout << j << "\t" << x << endl;
x=0;
应该可以解决问题。
关于C++ 随机数生成器 For 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19232409/