Is there a difference between random in C and random in Java?
As I am rewriting an application that often uses randoms from C to Java, and I would like to ask if there is any critical difference between
rand() % 256; // C code
and this one
import java.util.Random;
...
Random rand = new Random();
rand.nextInt(256);
Does anyone know if it works the same or, as I already wrote, is there some critical difference?
source to share
I will mostly answer with @ Mureinik's answer and just add that you should be aware that the C version does not provide evenly spaced numbers due to module work (IIRC RAND_MAX
should split evenly on n
as it does).
If that's important to you, you probably shouldn't use it rand()
anyway, though ...
Greetings,
source to share
You should not use the mod operator %
to narrow the random range, because the probability of the numbers will not be the same. For example, if RAND_MAX
equal to 256, the number 1 will have a higher probability than rest.
You can check this in Python, about twice as many zeros:
>>> sorted([(random.randint(0, 2) % 2) for x in range(100)])
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
To get the same probabilistic probability as the Java Cone from C, you should do something like:
/* Returns a random number from 0 to limit inclusive */
int rand_int(int limit) {
return ((long long)limit * rand()) / RAND_MAX
}
source to share