can you please tell me how rand () is implemented ? i know it is library implementaion dependent. but still can you tell me the way in which it is mostly implemented ? i have searched on google, but didn't get anything which make me clear about my question. i want to know algo or which code snippet are they using and how srand() helps that function ? thanks.

Recommended Answers

This might help you Tutorials Point

Jump to Post

but still can you tell me the way in which it is mostly implemented ?

rand() is usually implemented with some form of linear congruential generator.

Jump to Post

All 6 Replies

thanks rahul. but i am talking about the implementaion part. i already know all these things. thanks for reply.

Click Here to find out how random(pseudo) numberare generated.

As you stated, it is entirely up to the implementer how they achieve this, and they are free to do it however they like. Here is one way it has been done, in glibc Version 2.15; the call to rand ends up at the function __random_r in this implementation

http://sourceware.org/git/?p=glibc.git;a=blob;f=stdlib/random_r.c;hb=glibc-2.15#l361

I suspect this is the code you're looking for:
val = ((state[0] * 1103515245) + 12345) & 0x7fffffff;

In simplest terms, you have a table of numbers in pre-determined but guassian or semi random order. If you pick a random starting point (seed), then you'll get what appears to be a random result.

but still can you tell me the way in which it is mostly implemented ?

rand() is usually implemented with some form of linear congruential generator.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.