Python3 Random module code detail

  • 2020-06-15 09:23:13
  • OfStack

describe

The random() method returns a randomly generated real number in the range of [0,1].


import random
help(random)
FUNCTIONS
  betavariate(alpha, beta) method of Random instance #  Method of random instances 
    Beta distribution. #  Beta distribution 
    
    Conditions on the parameters are alpha > 0 and beta > 0. #  Must pass in more than 0 the alpha  with beta parameter 
    Returned values range between 0 and 1. #  return 1 a 0 -1  Between the value, the value you are random! 
    a = random.betavariate(999999, 99999999999999999) #  The first 1 Execution results: 9.995974671839104e-12  The first 2 Execution results: 1.0006927848540756e-11
     Beta distribution ( Beta Distribution)  is 1 The sum is distributed as Bernoulli 2 The density function of the conjugate prior distribution of the term distribution has important applications in machine learning and mathematical statistics. 
     In probability theory, the beta distribution, also called Β distribution, mean 1 Set of definitions in (0,1)  The continuous probability distribution of the interval. 
  
  choice(seq) method of Random instance
    Choose a random element from a non-empty sequence. #  Random from 1 Take out of a sequence that is not empty 1 The parameters must not be empty 
    Python contains  6  A built-in sequence of species, including lists, tuples, strings, Unicode String, buffer The objects and xrange Object. 
  
  choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance #  Method of random instances 
    Return a k sized list of population elements chosen with replacement. #  through chosen with replacement (That is, every time the selection opportunity is the same or according to the weight, the former choice will not affect the probability of the latter choice) 1 by k A random list of elements 
    
    If the relative weights or cumulative weights are not specified, #  If relative or cumulative weights are not specified, 
    the selections are made with equal probability.          #  The probability of choosing is equal. 
     from population Medium random extraction k Three elements (repeatable). Two parameters cannot exist simultaneously. 
     Example: 
    print(random.choices(['red', 'black', 'green'], [18, 18, 2], k=6) ) #  In order to 18 Take the probability weight of red . 18 Take the probability weight of black . 2 Take the probability weight of green , a total of 6 time 
    
    trial = lambda: random.choices('HT', cum_weights=(0.60, 1.00), k=7).count('H') >= 5 # H Is the probability that 0.6 . T Is the probability that 0.4
    print(sum(trial() for i in range(10000)) / 10000)

    trial2 = lambda : 2500 <= sorted(random.choices(range(10000), k=5))[2] < 7500
    print(sum(trial2() for i in range(10000)) / 10000 )

    from statistics import mean
    data = 1, 2, 4, 4, 10
    means = sorted(mean(random.choices(data, k=5)) for i in range(20)) # mean The average is o 
    print(f'The sample mean of {mean(data):.1f} has a 90% confidence ' 
   f'interval from {means[1]:.1f} to {means[-2]:.1f}') #  Here, f usage  
    #  Above programmed 3 The execution results are as follows: 
    # The sample mean of 4.2 has a 90% confidence interval from 2.4 to 6.6
    # The sample mean of 4.2 has a 90% confidence interval from 2.6 to 7.2
    # The sample mean of 4.2 has a 90% confidence interval from 2.0 to 7.0

  expovariate(lambd) method of Random instance #  Method of random instances 
    Exponential distribution. #  An index distribution 
    
    lambd is 1.0 divided by the desired mean. It should be
    nonzero. (The parameter would be called "lambda", but that is
    a reserved word in Python.) Returned values range from 0 to
    positive infinity if lambd is positive, and from negative
    infinity to 0 if lambd is negative.
     Lambda ( lambd ) is 1 Divided by the number you need, it can't be zero. The parameters should be called lambda , but it is python Reserved words) 
     This function returns 1 a 0 Random Numbers to positive infinity (if   Lambda.   Is positive), or returns 1 Minus infinity to zero 0 Random number if (if)   Lambda.   Negative) 
  
  gammavariate(alpha, beta) method of Random instance #  Method of random instances 
    Gamma distribution. Not the gamma function! #  Gamma distribution . not gamma function 
    
    Conditions on the parameters are alpha > 0 and beta > 0. #  Parameters are conditional on both parameters being greater than 0
    
    The probability distribution function is: #  The probability distribution function is: 
    
          x ** (alpha - 1) * math.exp(-x / beta)
     pdf(x) = --------------------------------------
           math.gamma(alpha) * beta ** alpha
  
  gauss(mu, sigma) method of Random instance #  Method of random instances 
    Gaussian distribution. #  The Gaussian distribution, also known as the normal or normal distribution 
    
    mu is the mean, and sigma is the standard deviation. This is 
    slightly faster than the normalvariate() function.
    
    Not thread-safe without a lock around calls.
    # mu As expected, sigma Is the variance, the ratio of this function normalvariate() The function has to be fast 1 A little 
    #  No thread call, thread is not safe. 
    #  There are two necessary parameters, mu with sigma . 
  
  getrandbits(...) method of Random instance #  Method of random instances 
    getrandbits(k) -> x. Generates an int with k random bits. #  Returns as an integer k Random bits ( 2 Base number). This function is especially useful if you are dealing with truly random transactions, such as encryption. 
  
  getstate() method of Random instance #  Method of random instances 
    Return internal state; can be passed to setstate() later. #  Returns an object that captures the internal state of the current generator . This object can be used for functions setstate() To save the current state .
  
  lognormvariate(mu, sigma) method of Random instance #  Method of random instances 
    Log normal distribution.
     Lognormal distribution ( logarithmic normal distribution ) refers to 1 The logarithm of the random variable obeys the normal distribution, then the random variable obeys the logarithm normal distribution. 
     The logarithmic normal distribution is very close to the normal distribution in the short run. But in the long run, the logarithmic normal distribution goes up more 1 Some. 
    
    If you take the natural logarithm of this distribution, you'll get a
    normal distribution with mean mu and standard deviation sigma.
    mu can have any value, and sigma must be greater than zero.
    #  If you take the natural log of the parameters of this distribution, you'll get 1 A mean for mu , the standard deviation is sigma Is a normal distribution. 
    # mu The parameter is any value, sigma Parameter must be greater than 0
  
  normalvariate(mu, sigma) method of Random instance #  Method of random instances 
    Normal distribution. #  The normal distribution, also known as the normal distribution and the Gaussian distribution 
    
    mu is the mean, and sigma is the standard deviation. # mu As expected, sigma For the variance 
  
  paretovariate(alpha) method of Random instance #  Method of random instances 
    Pareto distribution. alpha is the shape parameter. #  Pareto distribution ; parameter alpha Is the shape parameter 
    #  Pareto distribution (Pareto distribution) Named after the Italian economist Vilfredo Pareto,   A power law distribution found in a number of real-world phenomena, 
    #  This distribution, outside economics, is also known as the Bradford distribution. Pareto versus Italy 20% Population owned by 80% The property was famous for its observation, later by Joseph Juran and 
    #  Others generalize it as pareto's law ( 80/20 The law), later on 1 Step generalizes to the concept of pareto distribution. 

  
  randint(a, b) method of Random instance #  Method of random instances 
    Return random integer in range [a, b], including both end points. #  return a to b Between the 1 A random integer a and b
    #  You must pass in two parameters, and a, b Must be an integer, can be a negative integer ,a The parameter must be less than or equal to b Parameters. 
  
  random(...) method of Random instance #  Method of random instances 
    random() -> x in the interval [0, 1). #  No parameters, generated 1 a 0-1 The random number between, could be 0 But it doesn't 1
  
  randrange(start, stop=None, step=1, _int=<class 'int'>) method of Random instance #  Method of random instances 
    Choose a random item from range(start, stop[, step]). #  Random from 1 From a range of 1 A parameter 
    
    This fixes the problem with randint() which includes the #  This function is fixed randint() Can take the number to the right of the range 
    endpoint; in Python this is usually not what you want.  # randint() The situation where you can pick a range on the right is usually something that a lot of people don't want to see 
     Arguments must be integers, start Less than stop parameter 
  
  sample(population, k) method of Random instance #  Method of random instances 
    Chooses k unique random elements from a population sequence or set. #  from 1 a population Take out of a sequence or set k Three random elements 
    
    Returns a new list containing elements from the population while  #  return 1 The original sequence or collection does not change. 
    leaving the original population unchanged. The resulting list is 
    in selection order so that all sub-slices will also be valid random #  The list of returned items is in selected order. In this case, all sub-slices will also be legitimate random samples. 
    samples. This allows raffle winners (the sample) to be partitioned #  This allows the lucky ones in the sample to be selected to press the list 1 Name of the first 2 Names in this order (in the returned list) 
    into grand prize and second place winners (the subslices).
    
    Members of the population need not be hashable or unique. If the  # population The members of the sequence need not be hashed or identical. 
    population contains repeats, then each occurrence is a possible   #  if population The sequence contains duplicate members, so each selection is a possible selection in the sample 
    selection in the sample.
    
    To choose a sample in a range of integers, use range as an argument #  In order to 1 Choose from an integer range 1 A sample, please use the range value as 1 A parameter. 
    This is especially fast and space efficient for sampling from a   #  Doing so will be very fast and save memory when sampling large amounts of data 
    large population:  sample(range(10000000), 60)           #  Example: sample(range(10000000), 60)
  
  seed(a=None, version=2) method of Random instance #  Method of random instances 
    Initialize internal state from hashable object.          #  Initializes internal state with a hashed object 
    
    None or no argument seeds from current time or from an operating #  Parameters for None Or in the case of no parameters, then seeds Choose the value for yourself based on the current time 
    system specific randomness source if available.          #  Or from a random source specific to the system (if possible) 
    
    If *a* is an int, all bits are used.               #  If the parameter a Is an integer, all of them bits Bits will be used 
    
    For version 2 (the default), all of the bits are used if *a* is a str, #  when version Parameters for 2 (Default parameter) , If the parameter a is 1 Of string type, bytes or bytearray , then all of them bits Bits will be used 
    bytes, or bytearray. For version 1 (provided for reproducing random  #  when version Parameters for 1 When (available from old version python , the randomly generated sequence) 
    sequences from older versions of Python), the algorithm for str and   #  Based on the str,bytes Algorithm generation of 1 A narrow range of seeds. 
    bytes generates a narrower range of seeds.
  
  setstate(state) method of Random instance #  Method of random instances 
    Restore internal state from object returned by getstate(). #  save getstate() The object that gets and returns. 
  
  shuffle(x, random=None) method of Random instance #  Method of random instances 
    Shuffle list x in place, and return None. #  Disturb the list x And return None x Is a required pass list parameter 
    
    Optional argument random is a 0-argument function returning a #  Optional parameter is 1 A return without parameters 0-1 Function between floating point Numbers 
    random float in [0.0, 1.0); if it is the default None, the   #  If the optional parameter is the default None, It will use random.random Function method 
    standard random.random will be used.
     If you have 1 A better random number generator, or you have one 1 A random number generator suitable for your application, so you can use it instead of using the system default. 
  
  triangular(low=0.0, high=1.0, mode=None) method of Random instance #  Method of random instances 
    Triangular distribution. # 3 Angular distribution (triangular distribution) , also known as the Simpson distribution or 3 The angular distribution 
    
    Continuous distribution bounded by given lower and upper limits, # 3 The angular distribution is low limit of theta low , the upper limit for high The mode defaults to the continuous probability distribution of the mean of the two. 
    and having a given mode value in-between.
    
    http://en.wikipedia.org/wiki/Triangular_distribution
  
  uniform(a, b) method of Random instance #  Method of random instances 
    Get a random number in the range [a, b) or [a, b] depending on rounding. #  from a with b Take between 1 Random Numbers, 1 I'm sure I can get it a . b Let's see if we can get it b rounding 
    a b Two parameters must be, can be integer can be floating point, so far I know to get b The use of math.ceil
     What this method returns is 1 A random number 
  
  vonmisesvariate(mu, kappa) method of Random instance #  Method of random instances 
    Circular data distribution. #  Circular data distribution or von Mises distribution 
    
    mu is the mean angle, expressed in radians between 0 and 2*pi, and
    kappa is the concentration parameter, which must be greater than or
    equal to zero. If kappa is equal to zero, this distribution reduces
    to a uniform random angle over the range 0 to 2*pi.
    # mu  Is a measure of location, its gathering in 0-2*pi Between, kappa Is a measure of concentration that must be greater than or equal to 0 . 
    #  if kappa Is equal to the 0 , the distribution is uniform. For very small, the distribution is approximately uniform, measured at 0-2*pi between 

  
  weibullvariate(alpha, beta) method of Random instance
    Weibull distribution. #  Weibull distribution 
    
    alpha is the scale parameter and beta is the shape parameter. #  Lambda. >0 Is the proportional parameter ( scale parameter ), k>0 Is the shape parameter ( shape parameter ) 
    #  Here, alpha Is the proportional parameter, beta Is the shape parameter 
     Weibull distribution ( Weibull distribution ), also known as weber distribution or Weibull distribution, is the theoretical basis of reliability analysis and life testing. 
     Weibull distribution: widely used in reliability engineering, especially for mechanical and electrical products wear cumulative failure distribution. Since it can easily infer its distribution parameters from probability values, 
     It is widely used in data processing of various life tests. 

conclusion

That is the end of this article on Python3 Random module code detail, I hope to help you. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!


Related articles: