I have implemented a 1D random walk in C++ and Python; however, in both programs the expected value is not sqrt(N). I am wondering if there is a logic error in my code or some hidden factor that is making my outcome consistently low.
For those unfamiliar with random walk, the expected RMS value is sqrt(N). More info found here: http://ift.tt/1xUVl46
I consistently get about 80% of sqrt(N), for example:
N = 100, outcome = 80,79,81,78...
N = 25, outcome = 3.9, 4.1, 4.2, 3.8...
Code below:
#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;
}
I get the same outputs with my python code as well.
import random
def rand_walk():
walk = 0
for i in range(9):
rand = random.randint(0,1)
if(rand == 0):
walk = walk + 1
else:
walk = walk - 1
return walk
absolute = 0.0
numtrial = 100
for j in range(numtrial):
walk = rand_walk()
absolute = absolute + (walk**2)**(1/2.0)
print "Average Absolute Distance ", absolute/numtrial
I expect to get sqrt(n) but always get less, which makes me wonder if I am doing something wrong or thinking about the problem wrong.
Aucun commentaire:
Enregistrer un commentaire