C language - rand() datatype (max value)
John Kauffman
Posts: 653
In one source I see Propeller C rand() generates from 0 to 2,147,483,647, implying data type of int.
But I generated 100k rand() values and got a range from 0 to 32767 implying a data type of short int, just the positives.
A general C reference said it depends on the implementation.
Can anyone confirm the data type, or why my test for max is 32767 instead of 2,147,483,647?
test code:
#include "simpletools.h"
int main(void)
{
srand(CNT);
int myRandNew=1; int countTrial=1;
int maxSoFar=1; int minSoFar=1;
for(countTrial;countTrial<=100000;countTrial++){
myRandNew=rand();
if(myRandNew>maxSoFar) maxSoFar=myRandNew;
if(myRandNew<minSoFar) minSoFar=myRandNew;
}//for
print("count of trials %d\nminSoFar=%d\tmaxSoFar=%d\n",countTrial,minSoFar,maxSoFar);
}
But I generated 100k rand() values and got a range from 0 to 32767 implying a data type of short int, just the positives.
A general C reference said it depends on the implementation.
Can anyone confirm the data type, or why my test for max is 32767 instead of 2,147,483,647?
test code:
#include "simpletools.h"
int main(void)
{
srand(CNT);
int myRandNew=1; int countTrial=1;
int maxSoFar=1; int minSoFar=1;
for(countTrial;countTrial<=100000;countTrial++){
myRandNew=rand();
if(myRandNew>maxSoFar) maxSoFar=myRandNew;
if(myRandNew<minSoFar) minSoFar=myRandNew;
}//for
print("count of trials %d\nminSoFar=%d\tmaxSoFar=%d\n",countTrial,minSoFar,maxSoFar);
}
Comments
"The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive"
However it does not say what RAND_MAX might be.
It goes on to:
"POSIX.1-2001 gives the following example of an implementation of rand() and srand(), possibly useful when one needs the same sequence on two different machines.
All in all I would never use rand(). Firstly because it is generally a really bad pseudo random number generator and secondly because it is not thread safe (for that you should use rand_r()).
Like many C standard functions it is to be avoided.
Can you printf the value of RAND_MAX ? That will tell you something.
... and reading lib/stdlib/rand.c ...
...looks like propgcc4's lib produces 15-bit random integers...
(propgcc4-1.9.whatsowver-version here...)
I tried below but rand_max not recognized (tried UC and LC). Do I have to do something more to "pull it out from the library"?
John Abshier
Wow thanks for the heads up on PGC. Melissa O'Neill's lecture on random number generators is a real treat for us random nerds.
I had not realized there were such recent developments in PRNGs and statistical tests for randomness. (TestU01)
Somewhere here I posted a Spin object for the jkiss32 PRNG, a version of George Marsaglia's KISS algorithm, which dates back to 1999 http://www.math.niu.edu/~rusin/known-math/99/RNG, looks like we now need a Spin / PASM PGC!