我已经在C ++和Python中实现了一维随机游走;但是,在两个程序中,期望值不是sqrt(N)。我想知道我的代码中是否存在逻辑错误或某些隐藏因素导致我的结果一直很低。
对于那些不熟悉随机游走的人来说,预期的RMS值是sqrt(N)。更多信息请访问:http://www.mit.edu/~kardar/teaching/projects/chemotaxis(AndreaSchmidt)/random.htm
我一直得到大约80%的sqrt(N),例如:
N = 100,结果= 80,79,81,78 ......
N = 25,结果= 3.9,4.1,4.2,3.8 ......
以下代码:
# IMPORT DATAFRAME FROM PANDAS AS WELL AS PANDAS ITSELF
from pandas import DataFrame
import pandas as pd
import os
# OUR GOAL IS:::
# LOOP THROUGH THE FOLDER: excelDir.....
# AT EACH ITERATION IN THE LOOP, CHECK IF THE CURRENT FILE IS AN EXCEL FILE,
# IF IT IS, SIMPLY CONVERT IT TO CSV AND SAVE IT:
for fileName in os.listdir(excelDir):
#DO WE HAVE AN EXCEL FILE?
if fileName.endswith(".xls") or fileName.endswith(".xlsx"):
#IF WE DO; THEN WE DO THE CONVERSION USING PANDAS...
targetXLFile = os.path.join(excelDir, fileName)
targetCSVFile = os.path.join(csvDir, fileName) + ".csv"
# NOW, WE READ "IN" THE EXCEL FILE
dFrame = pd.read_excel(targetXLFile)
# ONCE WE DONE READING, WE CAN SIMPLY SAVE THE DATA TO CSV
pd.DataFrame.to_csv(dFrame, path_or_buf=targetCSVFile)
我也使用我的python代码获得相同的输出。
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <math.h>
float random_walk(int i);
float checkrand(int i);
using namespace std;
int main(int argc, char* argv[]){
srand(time(NULL));
float absolute = 0;
int trials = 1000;
for(int i=0; i<trials; i++){
absolute += sqrt(pow(random_walk(atoi(argv[1])),2));
}
cout<<absolute/trials<<endl;
}
float random_walk(int i){
float walk = 0;
for(int j=0; j<i; j++){
if(rand()%2 == 0){
walk--;
}
else{
walk++;
}
}
return walk;
}
我希望得到sqrt(n)但总是得到更少,这让我想知道我做错了什么或者想错了这个问题。
答案 0 :(得分:0)
我主要使用Python,所以我会用那种语言回答。
您使用d2_list = []
for j in range(numtrial):
walk = rand_walk(N)
# absolute = absolute + (walk**2)**(1/2.0)
d2_list.append(walk**2)
result = (sum(d2_list) / len(d2_list))**(1/2.)
print "Average Absolute Distance ", result
计算的是sqrt(d ^ 2)的总和,但您必须采用的是sqrt之前的RMS。
enum class TestObjectClass : uint16_t
{
Zero = 0,
TestApple = 1,
TestOrange = 8,
TestBanana = 3,
};