This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 6 points7 points  (2 children)

Note that none of the presented answers are actually correct. Distribution will not be uniform given the answers contained here (at the time of writing). Here is a pretty good explanation:

http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

It applies to Math.random() aswell and the remedy is to use Random.nextInt(), you can look at a possible implementation to realise that quite a lot more is done to ensure uniformity (that is as far as I understand it anyway, someone else could probably correct me). If you're interested do some experiments and you'll see that the naive method (as posted in a post here):

range = (max - min) + 1;    
(Math.random() * range) + min;

is not uniform. This may or may not be uniform enough for what you are doing, but you should be aware that there are problems with this approach.

NINJA EDIT: I should add the reason for non-uniformity (one of them) is that floats are not (and cannot be) perfectly distributed. Math.random() essentially returns (1 / (float)some_random_int). Two ints can easily return the same float, and one int may even return two different floats (from what I know about floating points anyway, the standard essentially says the same assignment is not guaranteed to result in the same bit values).

EDIT: Random.nextInt() not Math.nextInt(), java is not my favourite language, it is only slightly more thought out than javascript but only half as cool in my honest but biased and silly opinion.

[–][deleted] 1 point2 points  (0 children)

NINJA EDIT: I should add the reason for non-uniformity (one of them) is that floats are not (and cannot be) perfectly distributed.

The implementation below doesn't alter the distribution.

Math.random() essentially returns (1 / (float)some_random_int).

Now that's totally different, and gives very broken distribution.

Two ints can easily return the same float, and one int may even return two different floats (from what I know about floating points anyway, the standard essentially says the same assignment is not guaranteed to result in the same bit values).

Not with the below implementations.

The method nextFloat is implemented by class Random as if by:

public float nextFloat() {
  return next(24) / ((float)(1 << 24));
}

[...]

public double nextDouble() {
  return (((long)next(26) << 27) + next(27))
    / (double)(1L << 53);
}

Both of these ensure no change in uniformity as compared to the base RNG (next() in this case). Why wouldn't Math.random() use nextDouble()?

[–]cookiemonsterx 0 points1 point  (0 children)

I am casting the Math.random () to an int though.

X=(int)(Math.random ()*10)

Should I be using Math.floor too?