Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a larger random number from the c function rand()

Tags:

c

random

I am in a coding environment where I only have access to some most basic c functions. #include'ing other lib is not feasible.

In this environment, I can call rand() which gives me a random number between 0 to 32767 inclusively(I think) in my environment. Is the following code the right logic to get a larger random number that is evenly distributed like/as rand()?

rnum = rand() * (32767 + 1) + rand();

like image 556
Fai Ng Avatar asked Mar 24 '23 04:03

Fai Ng


1 Answers

rnum = (rand() << 15) | rand() might be faster, but if you need good quality random numbers you should look for an external library. Built-in random functions are generally adequate only for the simplest applications.

like image 66
Lee Daniel Crocker Avatar answered Mar 29 '23 23:03

Lee Daniel Crocker