Forum Moderators: open

Message Too Old, No Replies

math.random

If your Still Interested

         

monkey

6:29 am on Mar 14, 2004 (gmt 0)

10+ Year Member



dont know if your still interested but Random generates between 0 and 1. Not including 0,1.

e.g. 0.1 .... .9
Here is the code and out put.

System.out.println(Math.random()+ " ");

0.6651426775925644

If you want the out put to include 1 to 10 then here is the code

System.out.println((int)(Math.random()*10)+" ");

qeantk

10:47 pm on Mar 21, 2004 (gmt 0)

10+ Year Member



(I'm new here, but isn't this a JavaSCRIPT forum?)

Anways, Java's Math.random is inclusive of 0, but not 1, which is as it should be, by my reasoning, otherwise you wouldn't get a proper distribution, because you would have this, if both were inclusive,

0-.099 0
.1-.19 1
.2-.29 2
....
.9-.99 9
1.0 10

which is eleven groupings, with one very rare one, which would probably crash things, as nobody would account for it, or this, if both were exclusive,

0.000...001 - .099 0
.1 - .19 1
.2 - .29 2
....
.9 - .99 9

with ten groupings, but the firt one disadvantaged. So having one end-point inclusive, and the other exclusive is the only way it really makes sense.

Given that Java truncates and the only zero is inclusive, you don't want to forget to add 1, as your offset, to get 1-10, as opposed to 0-9.

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

should be the general formula, I think and is commonly screwed up - you get a different, non-equivalent, version, whereever you look. The common mistake in javascript is to use round() and HEAVILY imbalance your distribution, by disfavoring the endpoints.