Forintegers, there is uniform selection from a range. For sequences, there isuniform selection of a random element, a function to generate a randompermutation of a list in-place, and a function for random sampling withoutreplacement.
On the real line, there are functions to compute uniform, normal (Gaussian),lognormal, negative exponential, gamma, and beta distributions. For generatingdistributions of angles, the von Mises distribution is available.
If a is omitted or None, the current system time is used. Ifrandomness sources are provided by the operating system, they are usedinstead of the system time (see the os.urandom() function for detailson availability).
Returns a non-negative Python integer with k random bits. This methodis supplied with the Mersenne Twister generator and some other generatorsmay also provide it as an optional part of the API. When available,getrandbits() enables randrange() to handle arbitrarily largeranges.
If a weights sequence is specified, selections are made according to therelative weights. Alternatively, if a cum_weights sequence is given, theselections are made according to the cumulative weights (perhaps computedusing itertools.accumulate()). For example, the relative weights[10, 5, 30, 5] are equivalent to the cumulative weights[10, 15, 45, 50]. Internally, the relative weights are converted tocumulative weights before making selections, so supplying the cumulativeweights saves work.
If neither weights nor cum_weights are specified, selections are madewith equal probability. If a weights sequence is supplied, it must bethe same length as the population sequence. It is a TypeErrorto specify both weights and cum_weights.
The weights or cum_weights can use any numeric type that interoperateswith the float values returned by random() (that includesintegers, floats, and fractions but excludes decimals). Weights are assumedto be non-negative and finite. A ValueError is raised if allweights are zero.
For a given seed, the choices() function with equal weightingtypically produces a different sequence than repeated calls tochoice(). The algorithm used by choices() uses floating-pointarithmetic for internal consistency and speed. The algorithm usedby choice() defaults to integer arithmetic with repeated selectionsto avoid small biases from round-off error.
Note that even for small len(x), the total number of permutations of xcan quickly grow larger than the period of most random number generators.This implies that most permutations of a long sequence can never begenerated. For example, a sequence of length 2080 is the largest thatcan fit within the period of the Mersenne Twister random number generator.
Returns a new list containing elements from the population while leaving theoriginal population unchanged. The resulting list is in selection order so thatall sub-slices will also be valid random samples. This allows raffle winners(the sample) to be partitioned into grand prize and second place winners (thesubslices).
Multithreading note: When two threads call this functionsimultaneously, it is possible that they will receive thesame return value. This can be avoided in three ways.1) Have each thread use a different instance of the randomnumber generator. 2) Put locks around all calls. 3) Use theslower, but thread-safe normalvariate() function instead.
mu is the mean angle, expressed in radians between 0 and 2*pi, and kappais the concentration parameter, which must be greater than or equal to zero. Ifkappa is equal to zero, this distribution reduces to a uniform random angleover the range 0 to 2*pi.
Class that uses the os.urandom() function for generating random numbersfrom sources provided by the operating system. Not available on all systems.Does not rely on software state, and sequences are not reproducible. Accordingly,the seed() method has no effect and is ignored.The getstate() and setstate() methods raiseNotImplementedError if called.
Sometimes it is useful to be able to reproduce the sequences given by apseudo-random number generator. By reusing a seed value, the same sequence should bereproducible from run to run as long as multiple threads are not running.
Economics Simulationa simulation of a marketplace byPeter Norvig that shows effectiveuse of many of the tools and distributions provided by this module(gauss, uniform, sample, betavariate, choice, triangular, and randrange).
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 Math.random() simpler to use. Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs. Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.Since:1.0See Also:Serialized FormConstructor SummaryConstructors Constructor and DescriptionRandom()Creates a new random number generator.Random(long seed)Creates a new random number generator using a single long seed.Method SummaryAll Methods Instance Methods Concrete Methods Modifier and TypeMethod and DescriptionDoubleStreamdoubles()Returns an effectively unlimited stream of pseudorandom double values, each between zero (inclusive) and one (exclusive).DoubleStreamdoubles(double randomNumberOrigin, double randomNumberBound)Returns an effectively unlimited stream of pseudorandom double values, each conforming to the given origin (inclusive) and bound (exclusive).DoubleStreamdoubles(long streamSize)Returns a stream producing the given streamSize number of pseudorandom double values, each between zero (inclusive) and one (exclusive).DoubleStreamdoubles(long streamSize, double randomNumberOrigin, double randomNumberBound)Returns a stream producing the given streamSize number of pseudorandom double values, each conforming to the given origin (inclusive) and bound (exclusive).IntStreamints()Returns an effectively unlimited stream of pseudorandom int values.IntStreamints(int randomNumberOrigin, int randomNumberBound)Returns an effectively unlimited stream of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).IntStreamints(long streamSize)Returns a stream producing the given streamSize number of pseudorandom int values.IntStreamints(long streamSize, int randomNumberOrigin, int randomNumberBound)Returns a stream producing the given streamSize number of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).LongStreamlongs()Returns an effectively unlimited stream of pseudorandom long values.LongStreamlongs(long streamSize)Returns a stream producing the given streamSize number of pseudorandom long values.LongStreamlongs(long randomNumberOrigin, long randomNumberBound)Returns an effectively unlimited stream of pseudorandom long values, each conforming to the given origin (inclusive) and bound (exclusive).LongStreamlongs(long streamSize, long randomNumberOrigin, long randomNumberBound)Returns a stream producing the given streamSize number of pseudorandom long, each conforming to the given origin (inclusive) and bound (exclusive).protected intnext(int bits)Generates the next pseudorandom number.booleannextBoolean()Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence.voidnextBytes(byte[] bytes)Generates random bytes and places them into a user-supplied byte array.doublenextDouble()Returns the next pseudorandom, uniformly distributed double value between 0.0 and 1.0 from this random number generator's sequence.floatnextFloat()Returns the next pseudorandom, uniformly distributed float value between 0.0 and 1.0 from this random number generator's sequence.doublenextGaussian()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.intnextInt()Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.intnextInt(int bound)Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.longnextLong()Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.voidsetSeed(long seed)Sets the seed of this random number generator using a single long seed.Methods inherited from class java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitConstructor DetailRandompublic Random()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.Randompublic Random(long seed)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 seedSee Also:setSeed(long)Method DetailsetSeedpublic void setSeed(long 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 - 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 bitsReturns:the next pseudorandom value from this random number generator's sequenceSince:1.1nextBytespublic void nextBytes(byte[] bytes)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 0; rnd >>= 8) bytes[i++] = (byte)rnd; Parameters:bytes - the byte array to fill with random bytesThrows:NullPointerException - if the byte array is nullSince:1.1nextIntpublic int nextInt()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 sequencenextIntpublic int nextInt(int bound)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 bound possible int values are produced with (approximately) equal probability. The method nextInt(int bound) is implemented by class Random as if by: public int nextInt(int bound) if (bound > 31); int bits, val; do bits = next(31); val = bits % bound; while (bits - val + (bound-1) 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:bound - the upper bound (exclusive). Must be positive.Returns:the next pseudorandom, uniformly distributed int value between zero (inclusive) and bound (exclusive) from this random number generator's sequenceThrows:IllegalArgumentException - if bound is not positiveSince:1.2nextLongpublic long nextLong()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)
3a8082e126