2 * Copyright (c) 2003-2005 The BISON Project
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU Lesser General Public License version 2 as
6 * published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Lesser General Public License for more details.
13 * You should have received a copy of the GNU Lesser General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 import java.util.Random;
22 import java.lang.Math;
25 * Extends the functionality of <code>java.util.Random</code>.
27 public class ExtendedRandom extends Random {
29 private long lastSeed;
31 // -------------------------------------------------------------------------
33 /** Calls super constructor. Also stores the seed to be returned by
34 {@link #getLastSeed}. */
35 public ExtendedRandom(long seed) {
41 // -------------------------------------------------------------------------
44 * Extracts the next integer, according to a Poisson distribution.
46 * @param mean The mean of the Poisson distribution.
47 * @return An integer Poisson extraction.
49 public int nextPoisson(double mean) {
51 double emean = Math.exp(-1 * mean);
55 while (product >= emean) {
56 product *= nextDouble();
58 count++; // keep result one behind
63 // -------------------------------------------------------------------------
66 * Implements nextLong(long) the same way nexInt(int) is implemented in
68 * @param n the bound on the random number to be returned. Must be positive.
69 * @return a pseudorandom, uniformly distributed long value between 0
70 * (inclusive) and n (exclusive).
72 public long nextLong(long n) {
75 throw new IllegalArgumentException("n must be positive");
77 if ((n & -n) == n) // i.e., n is a power of 2
79 return nextLong()&(n-1);
85 bits = (nextLong()>>>1);
88 while(bits - val + (n-1) < 0);
93 // -------------------------------------------------------------------------
95 /** Sets random seed. Calls super method but also stores the seed to be
96 returned by {@link #getLastSeed}. */
97 public void setSeed( long seed ) {
103 // -------------------------------------------------------------------------
106 * Returns the last random seed that was set explicitly. Either at
107 * construction time or through {@link #setSeed}.
109 public long getLastSeed() { return lastSeed; }
111 // -------------------------------------------------------------------------
114 public static void main(String[] args) {
116 ExtendedRandom er = new ExtendedRandom(12345678);
117 for(int i=0; i<100; ++i)
118 System.out.println(er.nextLong(Long.parseLong(args[0])));