From: <jim...@ag...> - 2003-03-27 15:50:13
|
I've experienced bad bahaviour when using $Math.random(int min, int = max) to generate pseudo-random integers. It seems like it always returns min, which when looking at the code = doesn't seem very strange: public static final int random(int start, int end) { return start + (int) (end *java.lang.Math.random()/(Integer.MAX_VALUE+1.0)); } Since java.lang.Math.random() returns a value between 0 and 1 and Integer.MAX_VALUE =3D 2^31 - 1 the division should always return almost zero, right? I may fail to understand the code, but it seems wrong to me so I = changed it to=20 public static final int random(int start, int end) { int iRet =3D start + (int) ((end - start + = 1)*java.lang.Math.random()); return iRet > end ? end : iRet; } The check shouldn't be neccesary, but better safe than sorry... :-) Any comments? ------------------------------------------------ Jimmy M=E4kel=E4 Programmerare Agent25 Sverige AB Slottsbacken 6 111 30 Stockholm Direkt: 08-534 80 423 Mobil: 073-623 05 51 ------------------------------------------------ Jag tycker att du borde anlita en agent. G=E5 till: www.agent25.se |