I have a code which creates an array of 1000 random entries and a routine which bins them in to a histogram. When I look at the results of the histogram I see that there are a lot more 0s than there should be. I can debug the code and I find that while my original array seems correct, after I pass the array to the next routine the last few entries are now 0. Furthermore, if I run a few more lines in the same routine, even more of the entries turn to 0. Does anyone have an idea as to what might be causing this?
Here is the code for reference:
int n = 1000;
int m = 100;
double r;
double *p;//line 22
p = generate_random( n ); //returns array of length n containing random numbers between 0 and 1
r = group(p, m, n);
...
double group(double* rnd, int m, int n)
{
int count[100] = { 0 };
int length = n;
int i, bin;//line 66
double dx = 1/(double) m;//length of each interval
for (i = 0; i < length; i++)
{
bin = (int) floor(*(rnd+i)/dx);//line 71
count[bin]++;//count[0] should be the number of random elements between 0 and 0.1
}
...//some more code that sets return double
When I enter the debugger at line 22 after creating p, I can see that p contains 1000 random numbers:
print *p = 0.78846
print *(p+851) = 0.3475
print *(p+999) = 0.9325
At line 66 it contains less:
print *rnd = 0.78846
print *(rnd+851) = 0.3475
print *(rnd+999) = 0
And at line 71 (i = 0) even less:
print *rnd = 0.78846
print *(rnd+851) = 6.9533e-310
print *(rnd+999) = 0
Edit: Here is the code for generate_random:
double * generate_random( int n )
{
const unsigned int a = 1664525;
const unsigned int b = 1013904223;
const unsigned int M = pow(2,32);
int i;
double random_numbers[n];
unsigned int rnd = time(NULL)%M; //number of seconds since 00:00 hours,
// Jan 1, 1970 UTC
for (i = 0; i < n; i++)
{
rnd = (a*rnd + b)%M;
random_numbers[i] = (double) rnd;
//map to [0,1]
random_numbers[i] = random_numbers[i]/M;
}
return random_numbers;
}
generate_random()? The issue could be with how you create your array.generate_random()(declarationdouble random_numbers[n];withna parameter to the function) don't do the same withint count[n];---instead ofint count[100];--- in the first functiongroup()? This way you won't make dimensioning mistakes.int count[n], so I figured I'd just get it to compile and work first and then worry about stuff like that.