Random Numbers

Mar 14, 2012 at 11:56pm
I've been writing some code that uses the rand() function and I have been noticing that the average number is not right in the middle of the set up slightly below it. This is demonstrated in this code i wrote
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <time.h>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<double> value;

double FillVec() {
    double random; 
    value.resize(10000);
    for(int i=0;i<10000;i++){
	  random = (rand() % 10000);
	   value[i] = random/10000;}  
   return 0;	   
}
   	   
double average(){
    double sum=0;
 for(int i=0;i<10000;i++){
  sum+=value[i];   
}
return (sum/(10000));   	   
}
   	   
   	   
int main() {
 srand( time(NULL) );
FillVec();
 cout<<"ave"<<average()<<endl;
}


the typical output value is around .47, but I was expecting a value of .5. I know this is a pseudo-random number generator so that could be why there is this problem. If so ford anyone know how to make a random number generator more random or how to fix up this existing one.
Mar 15, 2012 at 12:08am
What compiler are you using? When I run your code I get close to .5, sometimes slightly above and sometimes slightly below.
Mar 15, 2012 at 12:11am
I'm using Dev-C++. What are you using? I want that!
Last edited on Mar 15, 2012 at 12:11am
Mar 15, 2012 at 12:27am
gcc 4.7

What is the value of RAND_MAX? If it's very small that could be it. RAND_MAX is only 32767 on Microsoft's compiler. In that case when rand() returns values in the range 0-9999, 10000-19999, 20000-29999 (rand() % 10000) will on average give 5000 but when rand() returns values in the range 30000-32767 (rand() % 10000) will give on 1383,5 average. Because that is much lower it will make the total average value lower. A larger RAND_MAX makes the effects of this problem much smaller.
Mar 15, 2012 at 8:34pm
So i checked and found that RAND_MAX is in fact 32767 which makes sense because I am running a windows machine. Is there a way to increase it because if not i think i will just lower the range.
Mar 15, 2012 at 9:16pm
Use a different/better RNG?

Relevent:
http://cplusplus.com/forum/general/64495/
Mar 15, 2012 at 9:21pm
If you're looking for random number between 0 and 1 just calculate
 
rand()/RAND_MAX


Run this 10000 times, though you'll need a small bit of casting in there else you'll be getting 0s. Maybe just have double random = rand().
Last edited on Mar 15, 2012 at 9:22pm
Topic archived. No new replies allowed.