On Thu, Dec 21, 2006 at 12:34:12AM +0100, John Tromp wrote: > On 12/20/06, Peter Drake <[EMAIL PROTECTED]> wrote: > > > >I tried creating a random number generator > > > >java.util.Random rand = new java.util.Random() > > > >and then asking it for a random int > > > >rand.nextInt() > > > >which I would then take modulo the board size to choose a random > >point. Since ints in Java are signed, I would have to take the > >absolute value of this int before the modulo operaton. (As in C/C++, > >Java's % operator does not behave as modulo, in the mathematical > >sense, when the first argument is negative. It might more accurately > >be called "remainder".) > > > >This almost always works, but once in a very great while I would get > >a negative result anyway. I eventually hunted down the problem, which > >is explained in the API for the java.lang.Math.abs() method: > > > >"Note that if the argument is equal to the value of > >Integer.MIN_VALUE, the most negative representable int value, the > >result is that same value, which is negative." > > > >Yikes! > > > >So, I'll have to check the sign of my result and try again in those > >rare (but not ignorably rare) instances where it is negative. > > Or use (r & (-1>>1)) to obtain a nonnegative value (instead of abs(r)), > or use the nextInt(n) method...
Yes. Also note that generating the unsigned random samples as abs(r) from samples r distributed uniformly over some signed range tends to give only half the chance of getting zero as of getting any other number. Was that that what you wanted? The fact that the absolute value of the all-ones two's complement binary number overflows the unsigned range is not unrelated to the fact that the chance of getting zero absolute value is only half the chance of getting nonzero absolute value. Assuming that John's right-shift operator (in -1>>1) does what I hope it does, then it looks as though in his method the two facts cancel out so that the chance of a zero sample value is the same as any other sample value. I would tend to consider this a feature, but if you had been intentionally arranging for zero to be less likely, you might not agree. -- William Harold Newman <[EMAIL PROTECTED]> PGP key fingerprint 85 CE 1C BA 79 8D 51 8C B9 25 FB EE E0 C3 E5 7C Ubi saeva indignatio ulterius cor lacerare nequit. -- Jonathan Swift's epitaph _______________________________________________ computer-go mailing list [email protected] http://www.computer-go.org/mailman/listinfo/computer-go/
