KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > math > random > AbstractRandomGenerator


1 /*
2  * Copyright 2005 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.commons.math.random;
17
18 /**
19  * Abstract class implementing the {@link RandomGenerator} interface.
20  * Default implementations for all methods other than {@link #nextDouble()} and
21  * {@link #setSeed(long)} are provided.
22  * <p>
23  * All data generation methods are based on <code>nextDouble().</code>
24  * Concrete implementations <strong>must</strong> override
25  * this method and <strong>should</strong> provide better / more
26  * performant implementations of the other methods if the underlying PRNG
27  * supplies them.
28  *
29  * @since 1.1
30  * @version $Revision$ $Date: 2005-07-04 16:30:05 -0700 (Mon, 04 Jul 2005) $
31  */

32 public abstract class AbstractRandomGenerator implements RandomGenerator {
33     
34     /**
35      * Cached random normal value. The default implementation for
36      * {@link #nextGaussian} generates pairs of values and this field caches the
37      * second value so that the full algorithm is not executed for every
38      * activation. The value <code>Double.NaN</code> signals that there is
39      * no cached value. Use {@link #clear} to clear the cached value.
40      */

41     private double cachedNormalDeviate = Double.NaN;
42     
43     /**
44      * Construct a RandomGenerator.
45      */

46     public AbstractRandomGenerator() {
47         super();
48         
49     }
50     
51     /**
52      * Clears the cache used by the default implementation of
53      * {@link #nextGaussian}. Implemementations that do not override the
54      * default implementation of <code>nextGaussian</code> should call this
55      * method in the implementation of {@link #setSeed(long)}
56      */

57     public void clear() {
58         cachedNormalDeviate = Double.NaN;
59     }
60     
61     /**
62      * Sets the seed of the underyling random number generator using a
63      * <code>long</code> seed. Sequences of values generated starting with the
64      * same seeds should be identical.
65      * <p>
66      * Implementations that do not override the default implementation of
67      * <code>nextGaussian</code> should include a call to {@link #clear} in the
68      * implementation of this method.
69      *
70      * @param seed the seed value
71      */

72     public abstract void setSeed(long seed);
73
74     /**
75      * Generates random bytes and places them into a user-supplied
76      * byte array. The number of random bytes produced is equal to
77      * the length of the byte array.
78      * <p>
79      * The default implementation fills the array with bytes extracted from
80      * random integers generated using {@link #nextInt}.
81      *
82      * @param bytes the non-null byte array in which to put the
83      * random bytes
84      */

85     public void nextBytes(byte[] bytes) {
86         int bytesOut = 0;
87         while (bytesOut < bytes.length) {
88           int randInt = nextInt();
89           for (int i = 0; i < 3; i++) {
90               if ( i > 0) {
91                   randInt = randInt >> 8;
92               }
93               bytes[bytesOut++] = (byte) randInt;
94               if (bytesOut == bytes.length) {
95                   return;
96               }
97           }
98         }
99     }
100
101      /**
102      * Returns the next pseudorandom, uniformly distributed <code>int</code>
103      * value from this random number generator's sequence.
104      * All 2<font size="-1"><sup>32</sup></font> possible <tt>int</tt> values
105      * should be produced with (approximately) equal probability.
106      * <p>
107      * The default implementation provided here returns
108      * <pre>
109      * <code>(int) (nextDouble() * Integer.MAX_VALUE)</code>
110      * </pre>
111      *
112      * @return the next pseudorandom, uniformly distributed <code>int</code>
113      * value from this random number generator's sequence
114      */

115     public int nextInt() {
116         return (int) (nextDouble() * Integer.MAX_VALUE);
117     }
118
119     /**
120      * Returns a pseudorandom, uniformly distributed <tt>int</tt> value
121      * between 0 (inclusive) and the specified value (exclusive), drawn from
122      * this random number generator's sequence.
123      * <p>
124      * The default implementation returns
125      * <pre>
126      * <code>(int) (nextDouble() * n</code>
127      * </pre>
128      *
129      * @param n the bound on the random number to be returned. Must be
130      * positive.
131      * @return a pseudorandom, uniformly distributed <tt>int</tt>
132      * value between 0 (inclusive) and n (exclusive).
133      * @throws IllegalArgumentException if n is not positive.
134      */

135     public int nextInt(int n) {
136         if (n <= 0 ) {
137             throw new IllegalArgumentException JavaDoc("upper bound must be positive");
138         }
139         int result = (int) (nextDouble() * n);
140         return result < n ? result : n - 1;
141     }
142
143      /**
144      * Returns the next pseudorandom, uniformly distributed <code>long</code>
145      * value from this random number generator's sequence. All
146      * 2<font size="-1"><sup>64</sup></font> possible <tt>long</tt> values
147      * should be produced with (approximately) equal probability.
148      * <p>
149      * The default implementation returns
150      * <pre>
151      * <code>(long) (nextDouble() * Long.MAX_VALUE)</code>
152      * </pre>
153      *
154      * @return the next pseudorandom, uniformly distributed <code>long</code>
155      *value from this random number generator's sequence
156      */

157     public long nextLong() {
158         return (long) (nextDouble() * Long.MAX_VALUE);
159     }
160
161     /**
162      * Returns the next pseudorandom, uniformly distributed
163      * <code>boolean</code> value from this random number generator's
164      * sequence.
165      * <p>
166      * The default implementation returns
167      * <pre>
168      * <code>nextDouble() <= 0.5</code>
169      * </pre>
170      *
171      * @return the next pseudorandom, uniformly distributed
172      * <code>boolean</code> value from this random number generator's
173      * sequence
174      */

175     public boolean nextBoolean() {
176         return nextDouble() <= 0.5;
177     }
178
179      /**
180      * Returns the next pseudorandom, uniformly distributed <code>float</code>
181      * value between <code>0.0</code> and <code>1.0</code> from this random
182      * number generator's sequence.
183      * <p>
184      * The default implementation returns
185      * <pre>
186      * <code>(float) nextDouble() </code>
187      * </pre>
188      *
189      * @return the next pseudorandom, uniformly distributed <code>float</code>
190      * value between <code>0.0</code> and <code>1.0</code> from this
191      * random number generator's sequence
192      */

193     public float nextFloat() {
194         return (float) nextDouble();
195     }
196
197     /**
198      * Returns the next pseudorandom, uniformly distributed
199      * <code>double</code> value between <code>0.0</code> and
200      * <code>1.0</code> from this random number generator's sequence.
201      * <p>
202      * This method provides the underlying source of random data used by the
203      * other methods.
204      *
205      * @return the next pseudorandom, uniformly distributed
206      * <code>double</code> value between <code>0.0</code> and
207      * <code>1.0</code> from this random number generator's sequence
208      */

209     public abstract double nextDouble();
210
211     /**
212      * Returns the next pseudorandom, Gaussian ("normally") distributed
213      * <code>double</code> value with mean <code>0.0</code> and standard
214      * deviation <code>1.0</code> from this random number generator's sequence.
215      * <p>
216      * The default implementation uses the <em>Polar Method</em>
217      * due to G.E.P. Box, M.E. Muller and G. Marsaglia, as described in
218      * D. Knuth, <u>The Art of Computer Programming</u>, 3.4.1C.
219      * <p>
220      * The algorithm generates a pair of independent random values. One of
221      * these is cached for reuse, so the full algorithm is not executed on each
222      * activation. Implementations that do not override this method should
223      * make sure to call {@link #clear} to clear the cached value in the
224      * implementation of {@link #setSeed(long)}.
225      *
226      * @return the next pseudorandom, Gaussian ("normally") distributed
227      * <code>double</code> value with mean <code>0.0</code> and
228      * standard deviation <code>1.0</code> from this random number
229      * generator's sequence
230      */

231     public double nextGaussian() {
232         if (!Double.isNaN(cachedNormalDeviate)) {
233             double dev = cachedNormalDeviate;
234             cachedNormalDeviate = Double.NaN;
235             return dev;
236         }
237         double v1 = 0;
238         double v2 = 0;
239         double s = 1;
240         while (s >=1 ) {
241             v1 = 2 * nextDouble() - 1;
242             v2 = 2 * nextDouble() - 1;
243             s = v1 * v1 + v2 * v2;
244         }
245         if (s != 0) {
246             s = Math.sqrt(-2 * Math.log(s) / s);
247         }
248         cachedNormalDeviate = v2 * s;
249         return v1 * s;
250     }
251 }
252
Popular Tags