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?
Apart from possible differences in the probability distribution caused by the use of different pseudo-random algorithms, there is no difference between them: both fragments generate a number between zero and 255, including both ends.
In terms of functionality, both promise a (pseudo) random distribution int
ranging from [0..255]. The implementation specifications (like the PRNG algorithm used) may be different, but you really shouldn't rely on them anyway.
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,
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
}