Reputation: 389
I was curious to know why random_number=a+rand()%b;
in C produces a random number between a and b (non-inclusive of b). But in Java this code will not work. I understand that the correct way to do this in Java is random_number=a+(Math.random()*(b-a));
but I was curious to know why there is a difference? Isn't it the same operation mathematically? I also understand that the return types are different for the random functions, but how does this difference explain the difference in output? Sorry if this seems like a trivial question but I was curious nonetheless.
Upvotes: 0
Views: 3080
Reputation: 1181
In java it is nextInt()
int nextInt(int n)
This function returns random number between 0 to n
In C it is rand()
int rand(void)
This function returns an integer value between 0 and RAND_MAX.
Upvotes: 0
Reputation: 47729
One can, of course use java.util.Random's nextInt()
or nextInt(int n)
method to more exactly mimic the C scheme. nextInt()
is almost exactly the same as rand()
(though hopefully better distributed) while nextInt(int n)
effectively subsumes the %n
calculation.
Upvotes: 2
Reputation: 178263
The difference lies in what each random generator does.
In Java, Math.Random
returns a pseudo-random number of the range 0
(inclusive) through 1
(exclusive). So it must be scaled up by b - a
, the width of the range, then shifted by a
, the start of the range.
In C, rand()
returns numbers in the range 0
to RAND_MAX
(my RAND_MAX
is 32767
), so %b
is used to control the width of the range, and the start of the range is shifted by a
.
Upvotes: 6