[prog] Seeking and appropriate Java component
Riccarda Cassini
riccarda.cassini at gmx.de
Wed May 5 12:09:32 EST 2004
Sue Stones wrote:
> Another problem with the program, is that all the particles drift to
> the north west. I am using "Random" to produce the movements, but
> clearly "Random is biased. Any one know the solution to this? Here
> are the calls to Random.
>
> protected final Random rng = new Random();
>
> public synchronized void move() {
> x += rng.nextInt(10) - 5;
> y += rng.nextInt(20) - 10;
> } // move
Hey, a question I can actually *answer*! :-)
I think the bias is created by the way the method nextInt(n) is
defined: it returns an int value between 0 (inclusive) and n
(*exclusive*). Thus, for nextInt(10) you get values from 0..9.
Or, after subtracting 5, you have -5..+4, which surely is biased.
By using integers, you're essentially loosing 1 from the requested
range n (on the upper bound).
Using "rng.nextInt(11) - 5" should solve the problem, as you'll then
get values ranging from -5..+5.
Wiser heads than mine will have to comment on your other problem, though.
Ciao,
Riccarda
--
NEU : GMX Internet.FreeDSL
Ab sofort DSL-Tarif ohne Grundgebühr: http://www.gmx.net/dsl
More information about the Programming
mailing list