Implementation of rand() and srand()

Started by
6 comments, last by ????????? 12 years, 8 months ago
Hello all,
I need to know the exact implementation of rand() and srand(). I have to use in python that will give me the exact numbers that I get from C implementation.

Here is some code I found, is this correct??


static unsigned long int next = 1;

int rand(void) // RAND_MAX assumed to be 32767
{
next = next * 1103515245 + 12345;
return (unsigned int)(next/65536) % 32768;
}

void srand(unsigned int seed)
{
next = seed;
}
Advertisement
The rand implementation will probably change with compiler. What compiler are you interested in?
thanks for you reply. I am not sure, I am using Visual C++ 2008 Express edition with default settings. How can I find out?
I doubt youll find any documentation on microsoft's rand(). Is there a reason that you need to match a specific rand(), and not just use the same algorithim as your python in your C++ code
Yes I do because I have to use python. And I am porting code from C to python. When the C code was run in one environment it created reference images getting pixel values from random numbers. I need to make sure that I get identical images from ported code in the 2nd environment. this environment will only use python, not C.

So I need to implement the same rand implementation locally in my python code.
Actually I found the code in rand.c in Visual studio directory.
This is what they have but I don't really understand. Is this is the same as my original post? I don't understand bit shift >> :( Also what is "L" in the numbers?


void __cdecl srand (
unsigned int seed
)
{
_getptd()->_holdrand = (unsigned long)seed;
}



int __cdecl rand (
void
)
{
_ptiddata ptd = _getptd();

return( ((ptd->_holdrand = ptd->_holdrand * 214013L
+ 2531011L) >> 16) & 0x7fff );
}
I think the L is just saying that its a long, not an int. You can probably just omit in in Python, although Im not an expert. Shifting to the right by N is the same as dividing by 2 to the Nth power

I think the L is just saying that its a long, not an int. You can probably just omit in in Python, although Im not an expert. Shifting to the right by N is the same as dividing by 2 to the Nth power

Yes. the 'L' at the end is a long, you are correct.

This topic is closed to new replies.

Advertisement