Python STL Random

Source: Internet
Author: User
Tags generator shuffle

Effect: Many types of pseudo-random number generators are implemented.

Python version: 1.4 and later versions

The random module backbone Mersenne ivister algorithm provides a fast pseudo-random number generator. The generator was originally developed to generate input to the Monte Carlo simulation, and the Mersenne twister algorithm generates a number of near-uniform distributions with a large period to suit all types of applications.

Generate random numbers

The random () function returns the next random floating-point value from the generated sequence. All values returned fall within the 0< n <1.0 interval.

import randomfor i in xrange(5):    print '%04.3f' % random.random(),print

Running this program repeatedly produces a different sequence of numbers.

0.929 0.100 0.906 0.075 0.439[Finished in 0.1s]

To generate a number within a specified range of values, use uniform ().

import randomfor i in xrange(5):    print '%04.3f' % random.uniform(1, 100),print

Passing in the minimum and maximum values, uniform () uses the formula min + (max-min) * Random to adjust the return value of the random ().

4.679 66.794 19.423 44.725 5.482[Finished in 0.1s]
Specify seed

Each call to random generates a different value, and the number repeats after a very large period. This is useful for generating values of unique values or changes, although in some cases it may be necessary to provide the same data set, which is handled in the same way. For this, one technique is to use a program to generate random values and save these random values so that they can be processed separately by a single step. However, this may not be practical for large amounts of data, so random contains a seed () function that initializes the pseudo-random number generator so that it can generate an expected set of values.

import randomrandom.seed(1)for i in xrange(5):    print '%04.3f' % random.random(),print

The seed (seed) value controls the first value produced by the formula used to generate the pseudo-random number, and since the formula is deterministic, the entire sequence to be generated is set after the seed is changed. The parameters of the seed can be any hash object. The default is to use a platform-specific random source, such as Gao. Otherwise, if there is no such a random source, the current time is used.

0.134 0.847 0.764 0.255 0.495[Finished in 0.1s]
Save state

The internal state of the pseudo-random algorithm used by random can be saved and used to control the random number generated by subsequent rounds, and the previous state is resumed before the random number is generated, which reduces the likelihood that the previously entered values or sequence of values will be duplicated. The GetState function returns some data that can be used later to reinitialize the pseudo-random number generator with SetState.

import randomimport osimport cPickle as pickleif os.path.exists('state.dat'):    # Restore the previously saved state    print 'Found state.dat, initializing random module'    with open('state.dat', 'rb') as f:        state = pickle.load(f)    random.setstate(state)else:    # Use a well-known start state    print 'No state.dat, seeding'    random.seed(1)# Produce random valuesfor i in xrange(3):    print '%04.3f' % random.random(),print# Save state for next timewith open('state.dat', 'wb') as f:    pickle.dump(random.getstate(), f)# Produce more random valuesprint '\nAfter saving state:'for i in xrange(3):    print '%04.3f' % random.random(),print

The data returned by GetState () is an implementation detail, so this example saves the data to a file using pickle, but it can be used as a black box. If the file exists at the beginning of the program, the original state is loaded and continues. Each run will generate several numbers before and after the save state to show that the recovery status will cause the generator to generate the same values again.

No state.dat, seeding0.134 0.847 0.764After saving state:0.255 0.495 0.449[Finished in 0.1s]Found state.dat, initializing random module0.255 0.495 0.449After saving state:0.652 0.789 0.094[Finished in 0.1s]Found state.dat, initializing random module0.652 0.789 0.094After saving state:0.028 0.836 0.433[Finished in 0.1s]
Random integers

Random will generate a floating-point number. You can convert the results to integers, but it is easier to generate integers directly using Randint.

import randomprint '[1, 100]:',for i in xrange(3):    print random.randint(1, 100),print '\n[-5, 5]:',for i in xrange(3):    print random.randint(-5, 5),print

The Randint parameter is both ends of the closed interval of the value, which can be positive or negative, but the first value is less than the second value.

[1, 100]: 35 39 28 [-5, 5]: -3 4 4[Finished in 0.1s]

Randrange is a more general form of selecting values from an interval.

import randomfor i in xrange(3):    print random.randrange(0, 101, 5),print

In addition to the start value (start) and end value (stop), Randrange also supports a step step parameter, so it is completely equivalent to selecting a random value from range (Start,stop,step). But Randrange is more efficient because it does not have a really tectonic interval.

15 25 85[Finished in 0.1s]
Select random elements

A common use of the random number generator is to select elements from a sequence of enumeration values, even if the values are not numbers. The random includes a choice function that can be randomly selected in a sequence. The following example simulates tossing a coin 10,000 times, to count how many times face up, how many times face down,

import randomimport itertoolsoutcomes = { 'heads':0,             'tails':0,             }sides = outcomes.keys()for i in range(10000):    outcomes[ random.choice(sides) ] += 1print 'Heads:', outcomes['heads']print 'Tails:', outcomes['tails']

Since only two results are allowed, you do not have to use numbers and then convert, using the word "heads" (representing face-up) and "tails" (representing face-down) for choice. The results are stored as tables in a dictionary, using the result name as the key.

Heads: 5042Tails: 4958[Finished in 0.1s]
Arranged

To simulate a poker game, you need to mix up a deck of cards and then deal with the player, the same card can not be used multiple times. The use of choice may cause the same card to be issued two times, so you can use shuffle () to shuffle, and then delete the cards when the card is issued.

  Import Randomimport itertoolsface_cards = (' J ', ' Q ', ' K ', ' A ') suits = (' H ', ' D ', ' C ', ' S ') def New_deck (): RE Turn list (itertools.product (Itertools.chain (xrange (2, one), face_cards), suits,) def Sho W_deck (deck): P_deck = deck[:] While p_deck:row = p_deck[:13] P_deck = p_deck[13:] for J in Ro W:print '%2s%s '% J, print# make a new deck, with the cards in Orderdeck = New_deck () print ' Initial Dec K: ' Show_deck (deck) # Shuffle the deck to randomize the Orderrandom.shuffle (deck) print ' \nshuffled deck: ' Show_deck (deck) # Deal 4 hands of 5 cards eachhands = [[], [], [], []]for i in xrange (5): For h in Hands:h.append (Deck.pop ()) # Show the Handsprint ' \nhands: ' for N, h in Enumerate (hands): print '%d: '% (n+1), for C in H:print '%2s%s '% C, Print # Show the remaining deckprint ' \nremaining deck: ' Show_deck (deck)  

These cards are expressed as tuples, consisting of a face value and a letter representing a suit. To create a hand that has been issued, you can add one card to 4 lists at a time, and then remove it from the deck so that the cards do not issue again.

Initial deck: 2H  2D  2C  2S  3H  3D  3C  3S  4H  4D  4C  4S  5H 5D  5C  5S  6H  6D  6C  6S  7H  7D  7C  7S  8H  8D 8C  8S  9H  9D  9C  9S 10H 10D 10C 10S  JH  JD  JC JS  QH  QD  QC  QS  KH  KD  KC  KS  AH  AD  AC  ASShuffled deck: 3C  8S  QC  5D  2C  9H  QH  KC  AS  4D  5H 10D  QS 3S  5S  JS  AD  QD  5C  KS  8H  4S  3H  7S 10C  6D 3D  2S  7D  4C  2H  9S  2D  6S  4H  6C  AC  JD  8D10H  KH  KD  JC  6H  9C  JH  7C 10S  8C  AH  9D  7HHands:1:  7H 10S  6H 10H  6C2:  9D  7C  JC  8D  4H3:  AH  JH  KD  JD  6S4:  8C  9C  KH  AC  2DRemaining deck: 3C  8S  QC  5D  2C  9H  QH  KC  AS  4D  5H 10D  QS 3S  5S  JS  AD  QD  5C  KS  8H  4S  3H  7S 10C  6D 3D  2S  7D  4C  2H  9S[Finished in 0.1s]
Sampling

Many simulations need to get random samples from a large number of input values the sample () function can generate samples with no duplicates, and the input sequence is not modified. The following example prints a random sample of the words in the system dictionary.

import randomwith open('words.txt', 'rt') as f:    words = f.readlines()words = [ w.rstrip() for w in words ]for w in random.sample(words, 5):    print w

The algorithm that generates the result set takes into account the size of the wheel and the requested sample, thus generating the results as efficiently as possible.

docibilityIturaeanyoudendriftsporidiumpansylike[Finished in 0.1s]Ituraeanpansylikejigamareedocibilityreadingdom[Finished in 0.1s]
Multiple and occurring generators

In addition to module-level functions, random also includes a random class to manage the internal state of multiple random number generators. All of the functions described earlier can be used as methods of the random instance, and each instance can be initialized and used independently, without interfering with the values returned by other instances.

import randomimport timeprint 'Default initializiation:\n'r1 = random.Random()r2 = random.Random()for i in xrange(3):    print '%04.3f  %04.3f' % (r1.random(), r2.random())print '\nSame seed:\n'seed = time.time()r1 = random.Random(seed)r2 = random.Random(seed)for i in xrange(3):    print '%04.3f  %04.3f' % (r1.random(), r2.random())

If a good built-in random value seed is set on the GAO system, the different instances will have a unique initial state. However, without a good platform random value generator, different instances tend to use the current time as a seed, so the same value is generated.

Default initializiation:0.189  0.3070.466  0.3280.020  0.757Same seed:0.510  0.5100.981  0.9810.679  0.679[Finished in 0.1s]

To ensure that the generator generates values from different parts of a random cycle, you can use Jumpahead to adjust the initial state of one of the generators.

Default initializiation:0.189  0.3070.466  0.3280.020  0.757Same seed:0.510  0.5100.981  0.9810.679  0.679[Finished in 0.1s]
Systemrandom

Some operating systems provide a random number generator that provides access to more sources of information that can be introduced into generators. Random provides this feature through the Systemrandom class, which is the same as the random API, but generates values using Os.urandom (), which forms the basis for all other algorithms.

import randomimport timeprint 'Default initializiation:\n'r1 = random.SystemRandom()r2 = random.SystemRandom()for i in xrange(3):    print '%04.3f  %04.3f' % (r1.random(), r2.random())print '\nSame seed:\n'seed = time.time()r1 = random.SystemRandom(seed)r2 = random.SystemRandom(seed)for i in xrange(3):    print '%04.3f  %04.3f' % (r1.random(), r2.random())

The sequences produced by Systemrandom are non-renewable because their randomness comes from the system, not from the software state (in fact, seed () and setstate () do not work at all).

Default initializiation:0.945  0.2010.767  0.2950.984  0.383Same seed:0.584  0.3240.598  0.6240.400  0.310[Finished in 0.1s]
Non-uniform distribution

The values generated by random are evenly distributed, which is useful for many purposes, but other distributions can more accurately model specific situations. The random module also contains functions to generate values for such distributions. These distributions are listed here, but are not intended to be described in detail because they are often used only under certain conditions and require more complex examples to illustrate.

Normal

Normal distribution (normal distribution) is often used for non-uniform continuous values, such as gradients, Gao degrees, resets, and so on. The normal distribution produces a curve with a unique shape, so it is nicknamed "Bell Curve". The random contains two functions that can generate a normal distribution value, divided by normalvariate and slightly faster Gauss. (A normal distribution is also known as the GAO distribution.) There is also a related function, lognormvariate, that generates pseudo-random values that are normally distributed to the logarithm. A logarithmic normal distribution applies to the product of multiple non-interactive random variables.

Approximate distribution

The triangular distribution is used for the approximate distribution of small samples. In the triangular distribution "curve", the lows are at the known minimum and maximum values, and there is a Gao point at the mode value, which is estimated according to the "closest" result (reflected by the Triangularo mode parameter).

Exponential distribution

Expovariate can generate an exponential distribution, which is useful for simulating arrival or interval values for homogeneous Poisson processes, such as the rate of radiation decay or requests to reach a Web server. Many observable phenomena apply to Pareto distribution or power-law distributions, which are popularized by Chris Anderson's "long Tail effect". The PARETOVARIATC () function is useful for Fumihiko resource allocation (man's financial palace, musician's needs, attention to blogs, etc.).

Angular distribution

Mises distribution or circular normal distribution (generated by vonmisesvariate) is used to calculate the probability of a period value, such as angle, calendar date, and time.

Size distribution

Betavariate generates values for beta distributions, which are commonly used in Bayesian statistics and applications such as task duration modeling. The gamma distribution generated by gammavariate () is used to model the size of things such as wait times, rainfall, and calculation errors. Weibullvariate calculates the Weber distribution for fault analysis, industrial engineering, and weather forecasts. It describes the size distribution of particles or other discrete objects.

Python STL Random

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.