Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
This is something that's been on my mind for years, but I never took the time to ask before. Many (pseudo) random number generators generate a random number between 0.0 and 1.0. Mathematically there are infinite numbers in this range, but double is a floating point number, and therefore has a finite precision. So the questions are: Just how many double numbers are there between 0.0 and 1.0?...
How can I convert a uniform distribution (as most random number generators produce, e.g. between 0.0 and 1.0) into a normal distribution? What if I want a mean and standard deviation of my choosing?
Two Questions: Will I get different sequences of numbers for every seed I put into it? Are there some "dead" seeds? (Ones that produce zeros or repeat very quickly.) By the way, which, if any, other PRNGs should I use? Solution: Since, I'm going to be using the PRNG to make a game, I don't need it to be cryptographically secure. I'm going with the Mersenne Twister, both for it's speed and h...
Is SecureRandom thread safe? That is, after initializing it, can access to the next random number be relied on to be thread safe? Examining the source code seems to show that it is, and this bug report seems to indicate that its lack of documentation as thread safe is a javadoc issue. Has anyone confirmed that it is in fact thread safe?
I want to generate random numbers in java, I know I should use existing methods like Math.random(), however, my question is: how can I generate the same sequence of numbers, each time I run my application? example: the generated sequence is: 0.9, 0.08,0.6 so I want that this sequence will be generated every time I execute this method..
I need to generate arbitrarily large random integers in the range 0 (inclusive) to n (exclusive). My initial thought was to call nextDouble and multiply by n, but once n gets to be larger than 253, the results would no longer be uniformly distributed. BigInteger has the following constructor available: public BigInteger(int numBits, Random rnd) Constructs a randomly generated BigInteger...
I don't know why I started thinking about this, but now I can't seem to stop. In C# - and probably a lot of other languages, I remember that Delphi used to let you do this too - it's legal to write this syntax: class WeirdClass { private void Hello(string name) { Console.WriteLine("Hello, {0}!", name); } public string Name { set { Hello(name); } } } ...
does someone of you know if there is a class in the standard library of .net, that gives me the functionality to create random variables that follow a gaussian distribution? Greets Sebastian
What I would like to do is shuffle the rows (read from CSV), then print out the first randomized 10,000 rows to one csv and the remainder to a separate csv. With a smaller file I can do something like java.util.Collections.shuffle(...) for (int i=0; i < 10000; i++) printcsv(...) for (int i=10000; i < data.length; i++) printcsv(...) However with very large files I now get OutOfMemoryEr...
I'm a little bit confused, how to do this. I know I can use Random class to generate random numbers, but I don't know how to specify and generate 8-byte number? Thanks, Vuk
I need a random number generator that generates various number between n and m, but no with a equal probability. I want to set a value x between n and m where the possibility is the highest: Is there an easy way to do that using the Random class? The likelihood should have the form of a binominal distribution or something similar (it is not important that its an exact binominal distributon, ...
Java's UUID class generates a random UUID. But this consists of alphabets and numbers. For some applications we need only numbers. Is there a way to generate random UUID that consists of only numbers in Java ? UUID.randomUUID();
Is it possible, from .NET, to mimic the exact randomization that Java uses? I have a seed, and I would like to be able to recieve the same results in both C# and Java when creating a random number.
Random class has a method to generate random int in a given range. For example: Random r = new Random(); int x = r.nextInt(100); This would generate an int number more or equal to 0 and less than 100. I'd like to do exactly the same with long number. long y = magicRandomLongGenerator(100); Random class has only nextLong(), but it doesn't allow to set range.
Simplified (i.e., leaving concurrency out) Random.next(int bits) looks like protected int next(int bits) { seed = (seed * multiplier + addend) & mask; return (int) (seed >>> (48 - bits)); } where masking gets used to reduce the seed to 48 bits. Why is it better than just protected int next(int bits) { seed = seed * multiplier + addend; return (int) (seed >>...
On Linux I am used to using mkpasswd to generate random passwords to use, on OS X however I don't have this command. Instead of sshing in to my vps every time, I wanted to re implement it using Java. What I have done is pick at random 4 lower case letters, 2 upper case letters, 2 symbols (/ . , etc) and 2 numbers. Then I create a vector and shuffle that too. Do you think this is good enough r...
I recently found myself needing to be sure my list wasn't in order. Hibernate was nice enough to return it in perfect order. Silly hibernate, not reading my mind. I looked at my Java API and it tells me its shuffle method does this: Randomly permutes the specified list using a default source of randomness. Being the curious george that I am, I want to know what exactly this means. Is ther...
Is there a way to get the value of a HashMap randomly in Java?
so when casting like in the statement below :- int randomNumber=(int) (Math.random()*5) it causes the random no. generated to get converted into an int.. Also there's this method I just came across Integer.parseInt() which does the same ! i.e return an integer Why two different ways to make a value an int ? Also I made a search and it says parseInt() takes string as an argument.. So does...
I'm using an OAuth library that calls new Random().nextLong() to generate nonces, however it generates the same nonce on asynchronous calls. I've narrowed it down to threading Random.nextLong() to returning the same exact number every so often. Does anyone know if this is a known limitation of Java? If so, does anyone know of a thread safe operation? EDIT: I'm using Java 1.6 EDIT: This is a...
I'm looking to randomize a BigInteger. The intent is to pick a number from 1 to 8180385048. Though, from what I noticed, the BigInteger(BitLen, Random) does it from n to X2-1, I'd want some unpredictable number. I tried to make a method that would do it, but I keep running into bugs and have finally given in to asking on here. :P Does anyone have any suggestions on how to do this?
  /*
   * Copyright 1995-2007 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;
 import java.io.*;
An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 3, Section 3.2.1.)

If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random. Java implementations must use all the algorithms shown here for the class Random, for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.

The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.

Many applications will find the method java.lang.Math.random() simpler to use.

Author(s):
Frank Yellin
Since:
1.0
 
 public
 class Random implements java.io.Serializable {
    
use serialVersionUID from JDK 1.1 for interoperability
 
     static final long serialVersionUID = 3905348978240129619L;

    
The internal state associated with this pseudorandom number generator. (The specs for the methods in this class describe the ongoing computation of this value.)
 
     private final AtomicLong seed;
 
     private final static long multiplier = 0x5DEECE66DL;
     private final static long addend = 0xBL;
     private final static long mask = (1L << 48) - 1;

    
Creates a new random number generator. This constructor sets the seed of the random number generator to a value very likely to be distinct from any other invocation of this constructor.
 
     public Random() { this(++ + System.nanoTime()); }
     private static volatile long seedUniquifier = 8682522807148012L;

    
Creates a new random number generator using a single long seed. The seed is the initial value of the internal state of the pseudorandom number generator which is maintained by method next(int).

The invocation new Random(seed) is equivalent to:

 Random rnd = new Random();
 rnd.setSeed(seed);

Parameters:
seed the initial seed
See also:
setSeed(long)
 
     public Random(long seed) {
         this. = new AtomicLong(0L);
         setSeed(seed);
     }

    
Sets the seed of this random number generator using a single long seed. The general contract of setSeed is that it alters the state of this random number generator object so as to be in exactly the same state as if it had just been created with the argument seed as a seed. The method setSeed is implemented by class Random by atomically updating the seed to
(seed ^ 0x5DEECE66DL) & ((1L << 48) - 1)
and clearing the haveNextNextGaussian flag used by nextGaussian().

The implementation of setSeed by class Random happens to use only 48 bits of the given seed. In general, however, an overriding method may use all 64 bits of the long argument as a seed value.

Parameters:
seed the initial seed
    synchronized public void setSeed(long seed) {
        seed = (seed ^ ) & ;
        this..set(seed);
         = false;
    }

    
Generates the next pseudorandom number. Subclasses should override this, as this is used by all other methods.

The general contract of next is that it returns an int value and if the argument bits is between 1 and 32 (inclusive), then that many low-order bits of the returned value will be (approximately) independently chosen bit values, each of which is (approximately) equally likely to be 0 or 1. The method next is implemented by class Random by atomically updating the seed to

(seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1)
and returning
(int)(seed >>> (48 - bits)).
This is a linear congruential pseudorandom number generator, as defined by D. H. Lehmer and described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.2.1.

Parameters:
bits random bits
Returns:
the next pseudorandom value from this random number generator's sequence
Since:
1.1
    protected int next(int bits) {
        long oldseednextseed;
        AtomicLong seed = this.;
        do {
            oldseed = seed.get();
            nextseed = (oldseed *  + ) & ;
        } while (!seed.compareAndSet(oldseednextseed));
        return (int)(nextseed >>> (48 - bits));
    }

    
Generates random bytes and places them into a user-supplied byte array. The number of random bytes produced is equal to the length of the byte array.

The method nextBytes is implemented by class Random as if by:

 public void nextBytes(byte[] bytes) {
   for (int i = 0; i < bytes.length; )
     for (int rnd = nextInt(), n = Math.min(bytes.length - i, 4);
          n-- > 0; rnd >>= 8)
       bytes[i++] = (byte)rnd;
 }

Parameters:
bytes the byte array to fill with random bytes
Throws:
java.lang.NullPointerException if the byte array is null
Since:
1.1
    public void nextBytes(byte[] bytes) {
        for (int i = 0, len = bytes.lengthi < len; )
            for (int rnd = nextInt(),
                     n = Math.min(len - i./.);
                 n-- > 0; rnd >>= .)
                bytes[i++] = (byte)rnd;
    }

    
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence. The general contract of nextInt is that one int value is pseudorandomly generated and returned. All 232 possible int values are produced with (approximately) equal probability.

The method nextInt is implemented by class Random as if by:

 public int nextInt() {
   return next(32);
 }

Returns:
the next pseudorandom, uniformly distributed int value from this random number generator's sequence
    public int nextInt() {
        return next(32);
    }

    
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence. The general contract of nextInt is that one int value in the specified range is pseudorandomly generated and returned. All n possible int values are produced with (approximately) equal probability. The method nextInt(int n) is implemented by class Random as if by:
 public int nextInt(int n) {
   if (n <= 0)
     throw new IllegalArgumentException("n must be positive");

   if ((n & -n) == n)  // i.e., n is a power of 2
     return (int)((n * (long)next(31)) >> 31);

   int bits, val;
   do {
       bits = next(31);
       val = bits % n;
    while (bits - val + (n-1) < 0);
   return val;
 }}

The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose int values from the stated range with perfect uniformity.

The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop terminates is 2.

The algorithm treats the case where n is a power of two specially: it returns the correct number of high-order bits from the underlying pseudo-random number generator. In the absence of special treatment, the correct number of low-order bits would be returned. Linear congruential pseudo-random number generators such as the one implemented by this class are known to have short periods in the sequence of values of their low-order bits. Thus, this special case greatly increases the length of the sequence of values returned by successive calls to this method if n is a small power of two.

Parameters:
n the bound on the random number to be returned. Must be positive.
Returns:
the next pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive) from this random number generator's sequence
Throws:
java.lang.IllegalArgumentException if n is not positive
Since:
1.2
    public int nextInt(int n) {
        if (n <= 0)
            throw new IllegalArgumentException("n must be positive");
        if ((n & -n) == n)  // i.e., n is a power of 2
            return (int)((n * (long)next(31)) >> 31);
        int bitsval;
        do {
            bits = next(31);
            val = bits % n;
        } while (bits - val + (n-1) < 0);
        return val;
    }

    
Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence. The general contract of nextLong is that one long value is pseudorandomly generated and returned.

The method nextLong is implemented by class Random as if by:

 public long nextLong() {
   return ((long)next(32) << 32) + next(32);
 }
Because class Random uses a seed with only 48 bits, this algorithm will not return all possible long values.

Returns:
the next pseudorandom, uniformly distributed long value from this random number generator's sequence
    public long nextLong() {
        // it's okay that the bottom word remains signed.
        return ((long)(next(32)) << 32) + next(32);
    }

    
Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence. The general contract of nextBoolean is that one boolean value is pseudorandomly generated and returned. The values true and false are produced with (approximately) equal probability.

The method nextBoolean is implemented by class Random as if by:

 public boolean nextBoolean() {
   return next(1) != 0;
 }

Returns:
the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence
Since:
1.2
    public boolean nextBoolean() {
        return next(1) != 0;
    }

    
Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.

The general contract of nextFloat is that one float value, chosen (approximately) uniformly from the range 0.0f (inclusive) to 1.0f (exclusive), is pseudorandomly generated and returned. All 224 possible float values of the form m x&nbsp2-24, where m is a positive integer less than 224 , are produced with (approximately) equal probability.

The method nextFloat is implemented by class Random as if by:

 public float nextFloat() {
   return next(24) / ((float)(1 << 24));
 }

The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose float values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as:

 return next(30) / ((float)(1 << 30));
This might seem to be equivalent, if not better, but in fact it introduced a slight nonuniformity because of the bias in the rounding of floating-point numbers: it was slightly more likely that the low-order bit of the significand would be 0 than that it would be 1.]

Returns:
the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence
    public float nextFloat() {
        return next(24) / ((float)(1 << 24));
    }

    
Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.

The general contract of nextDouble is that one double value, chosen (approximately) uniformly from the range 0.0d (inclusive) to 1.0d (exclusive), is pseudorandomly generated and returned.

The method nextDouble is implemented by class Random as if by:

 public double nextDouble() {
   return (((long)next(26) << 27) + next(27))
     / (double)(1L << 53);
 }

The hedge "approximately" is used in the foregoing description only because the next method is only approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen bits, then the algorithm shown would choose double values from the stated range with perfect uniformity.

[In early versions of Java, the result was incorrectly calculated as:

 return (((long)next(27) << 27) + next(27))
     / (double)(1L << 54);
This might seem to be equivalent, if not better, but in fact it introduced a large nonuniformity because of the bias in the rounding of floating-point numbers: it was three times as likely that the low-order bit of the significand would be 0 than that it would be 1! This nonuniformity probably doesn't matter much in practice, but we strive for perfection.]

Returns:
the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence
See also:
java.lang.Math.random()
    public double nextDouble() {
        return (((long)(next(26)) << 27) + next(27))
            / (double)(1L << 53);
    }
    private double nextNextGaussian;
    private boolean haveNextNextGaussian = false;

    
Returns the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence.

The general contract of nextGaussian is that one double value, chosen from (approximately) the usual normal distribution with mean 0.0 and standard deviation 1.0, is pseudorandomly generated and returned.

The method nextGaussian is implemented by class Random as if by a threadsafe version of the following:

 private double nextNextGaussian;
 private boolean haveNextNextGaussian = false;

 public double nextGaussian() {
   if (haveNextNextGaussian) {
     haveNextNextGaussian = false;
     return nextNextGaussian;
    else {
     double v1, v2, s;
     do {
       v1 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
       v2 = 2 * nextDouble() - 1;   // between -1.0 and 1.0
       s = v1 * v1 + v2 * v2;
     } while (s >= 1 || s == 0);
     double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
     nextNextGaussian = v2 * multiplier;
     haveNextNextGaussian = true;
     return v1 * multiplier;
   }
 }}
This uses the polar method of G. E. P. Box, M. E. Muller, and G. Marsaglia, as described by Donald E. Knuth in The Art of Computer Programming, Volume 3: Seminumerical Algorithms, section 3.4.1, subsection C, algorithm P. Note that it generates two independent values at the cost of only one call to StrictMath.log and one call to StrictMath.sqrt.

Returns:
the next pseudorandom, Gaussian ("normally") distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator's sequence
    synchronized public double nextGaussian() {
        // See Knuth, ACP, Section 3.4.1 Algorithm C.
        if () {
             = false;
            return ;
        } else {
            double v1v2s;
            do {
                v1 = 2 * nextDouble() - 1; // between -1 and 1
                v2 = 2 * nextDouble() - 1; // between -1 and 1
                s = v1 * v1 + v2 * v2;
            } while (s >= 1 || s == 0);
            double multiplier = StrictMath.sqrt(-2 * StrictMath.log(s)/s);
             = v2 * multiplier;
             = true;
            return v1 * multiplier;
        }
    }

    
Serializable fields for Random.

SerialField:
seed long seed for random computations
SerialField:
nextNextGaussian double next Gaussian to be returned
SerialField:
haveNextNextGaussian boolean nextNextGaussian is valid
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("seed".),
        new ObjectStreamField("nextNextGaussian".),
        new ObjectStreamField("haveNextNextGaussian".)
    };

    
Reconstitute the Random instance from a stream (that is, deserialize it).
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        ObjectInputStream.GetField fields = s.readFields();
        // The seed is read in as {@code long} for
        // historical reasons, but it is converted to an AtomicLong.
        long seedVal = (longfields.get("seed", -1L);
        if (seedVal < 0)
          throw new java.io.StreamCorruptedException(
                              "Random: invalid seed");
        resetSeed(seedVal);
         = fields.get("nextNextGaussian", 0.0);
         = fields.get("haveNextNextGaussian"false);
    }

    
Save the Random instance to a stream.
    synchronized private void writeObject(ObjectOutputStream s)
        throws IOException {
        // set the values of the Serializable fields
        ObjectOutputStream.PutField fields = s.putFields();
        // The seed is serialized as a long for historical reasons.
        fields.put("seed".get());
        fields.put("nextNextGaussian");
        fields.put("haveNextNextGaussian");
        // save them
        s.writeFields();
    }
    // Support for resetting seed while deserializing
    private static final Unsafe unsafe = Unsafe.getUnsafe();
    private static final long seedOffset;
    static {
        try {
             = .objectFieldOffset
                (Random.class.getDeclaredField("seed"));
        } catch (Exception ex) { throw new Error(ex); }
    }
    private void resetSeed(long seedVal) {
        .putObjectVolatile(thisnew AtomicLong(seedVal));
    }
New to GrepCode? Check out our FAQ X