i am up to build a Monte Carlo based simulation in C since it is super fast and I was wondering why my code is producing a even distribution.
So first to pick you up, bevor I started coding I imagened the picture of a few balls falling down and on every dot they can move left or right with random distribution. The picture is showen here: https://www.youtube.com/watch?v=PM7z_03o_kk.
But what I got is kind of strange. When I set the scatterpoints to 10 (which is in the code example setted to 100):
while(j < 100) // Number of abitrary change of direction
I got a picture like a Gauss-Distribution but only even bin´s are contributing to it. When its large enough like shown in the code, every bin got about the same amount of particles. This is the 2D case which will be expanded to the 3D case once it is working as expected.
There are still some Variables in it which are not really neccessary just to avoid any possible mistake I can imagine. I was working with gdb to find the error. When I just run distr() with gdb I figured out that it is producing only even numbers if the example above is setted to 10. When I go to 11 I found out, that bin[0] starts to contribute with a very small amout compared to the rest. I also ran rando() enough times to see if it's really pseudo-random and I found out that it should work.
I was still not able to figure out the mistake, so I really hope that here are enough people smarter than me oO.
Full code:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#define SEED time(NULL)
int rando(void) // Monte Carlo method for choosing weather left or right
{
double temp=0;
temp = (double) rand()/RAND_MAX; // pseudo random number between 0-1
if (temp >= 0.5)
return 1; // Particle to the right
if (temp < 0.5)
return 0; // Particle ot the left
else
return EXIT_FAILURE;
}
int distr(void) // Binning particle
{
int i=10; // Center of bin
int j=0;
int k=0;
while(j < 100) // Number of abitrary change of direction
{
k=rando();
if(k == 1)
{
if ( i < 13) // Choose upper bound of bins
i++;
j++;
}
if(k == 0)
{
if (i > 7) // Choose lower bound of bins
i--;
j++;
}
}
return i;
}
int main(void)
{
srand ( SEED );
int* bin;
int binning;
int k=0;
int l=0;
int iter;
fprintf(stdout, "\nIterations: ");
fscanf(stdin, "%d", &iter);
bin = malloc(21*sizeof(int));
while (k < 20)
{
bin[k] = 0;
k++;
}
k = 0;
while(k < iter) // Count of particle ot distribute
{
binning = distr(); // Choosing the bin
bin[binning]+=1; // Counting binned particle per bin
k++;
}
while(l < 20)
{
fprintf(stdout, "\n %d", bin[l]);
l++;
}
return EXIT_SUCCESS;
}
I can't wait to read you and thanks in advance, Maleware