Python random Introduction














































Python random Introduction



INTRODUCTION TO PYTHON random MODULE

 Python has a built-in random module that implements pseudo-random number generators for various distributions.This module contains methods that let us directly solve many different programming issues where randomness comes into play.
The random module is based on Marsenne Twister - a very popular algorithm, which is the default pseudo-random number generator not only for Python, but also for many other popular software systems such as Microsoft Excel, MATLAB, R, or PHP. Its important advantages include permissive licensing, random-likeness confirmed by many statistical tests, and relatively high speed compared to other pseudo random number generators.

What are Pseudo Random Number Generators ?

 In many programming cases, all we need are sets of numbers that seem random. This kind of data can be derived from pseudo-random number generators. These are algorithms, that use a tiny portion of information (called a seed) and then apply complicated mathematical formulas in order to generate deterministic sets of numbers resembling truly random sets.

How to use a random module?
 You need to import the random module in your program, and you are ready to use this module. Use the following statement to import the random module in your code.

import random

Code for some random module functions use:

Output:



random Module Functions :-

  • random() is the most basic function of the random module.
  • Almost all functions of the random module depend on the basic function random().
  • random() return the next random floating-point number in the range [0.0, 1.0).

   --> random module has a set of methods which are defined below :-


           Bookkeeping functions :


 
random.seed()

Initialize the random number generator.


random.getstate()

Return an object capturing the current internal state of the generator. This object can be passed to setstate() to restore the state.

random.setstate(state)

state should have been obtained from a previous call to getstate(), and setstate() restores the internal state of the generator to what it was at the time getstate() was called.

random.getrandbits(k)

Returns a Python integer with k random bits.

 


Functions for Integers :

random.randrange(stop)
random.randrange(startstopstep)
   Returns a randomly selected element from the given range.
random.randint(ab)

Return a random integer N such that a <= N <= b

    

Functions for Sequences :


random.choice(seq)

Return a random element from the non-empty sequence seq.  seq is empty will raises to index Error.

random.choices(seq,k=1)

Return a k sized list of elements chosen from the seq. If the seq is empty, raises index Error.

random.shuffle(x[random])

Take a sequence and returns the sequence in random order.

random.sample(seqk)

Return a k length list of unique elements chosen from the seq .


Real-valued distributions :

The following functions generate specific real-valued distributions. Function parameters are named after the corresponding variables in the distributions equation, as used in common mathematical practice; most of these equations can be found in any statistics text.

random.random()

Return the next random floating point number in the range [0.0, 1.0).

random.uniform(ab)

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.


random.triangular(lowhighmode)

Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

random.betavariate(alphabeta)

Returns a random float number between 0 and 1.Conditions on the parameters are alpha > 0 and beta > 0

random.expovariate(lmbd)

Exponential distribution. lmbd 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 lmbd is positive, and from negative infinity to 0 if lmbd is negative.

random.gammavariate(alphabeta)

Gamma distribution. (Not the gamma function!) Conditions on the parameters are alpha > 0 and beta > 0.

random.gauss(musigma)

Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below.

random.lognormvariate(musigma)

Log normal distribution. If you take the natural logarithm of this distribution, you get a normal distribution with mean mu and standard deviation sigmamu can have any value, and sigma must be greater than zero.

random.normalvariate(musigma)

Normal distribution. mu is the mean, and sigma is the standard deviation.

random.vonmisesvariate(mukappa)

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.

random.paretovariate(alpha)

Pareto distribution. alpha is the shape parameter.

random.weibullvariate(alphabeta)

Weibull distribution. alpha is the scale parameter and beta is the shape parameter.


Alternative Generator :


class random.Random([seed])

Class that implements the default pseudo-random number generator used by the random module.

class random.SystemRandom([seed])

Class that uses the os.urandom() function for generating random numbers from 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 raise NotImplementedError if called.



***Go and visit my next articles to learn more about every random module functions in details***

More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 92 0
Python string swapcase 80 0
Python string title 84 0
Python string startswith 89 0
Python string replace 134 0
Python string translate 72 0
Python string rpartition 76 0
Python string partition 66 0
Python string splitlines 95 0
Python string rsplit 65 0
Python string split 65 0
Python string rindex 73 0
Python string rfind 93 0
Python string upper 68 0
Python string lower 67 0
Python string maketrans 75 0
Python string strip 72 0
Python string rstrip 75 0
Python string lstrip 71 0
Python string rjust 81 0
Python string ljust 81 0
Python string len 70 0
Python string join 63 0
Python string casefold 68 0
Python string isprintable 70 0
Python string encode 68 0
Python string isdecimal 73 0
Python string isidentifier 65 0
Python string isupper 62 0
Python string istitle 69 0
Python string isspace 82 0
Python string isnumeric 87 0
Python string isdigit 68 0
Python string islower 72 0
Python string isalpha 82 0
Python string isalnum 78 0
Python string index 78 0
Python string find 82 0
Python string expandtabs() 73 0
Python string endswith 77 0
Python string count 72 0
Python string capitalize 64 0
Python string center 74 0
Python string Introduction 89 0
Python string Template 128 0
Python string Formatter 122 0
Python string printable 169 0
Python string whitespace 124 0
Python string punctuation 84 0
Python string octdigits 75 0
Python string hexdigits 89 0
Python string digits 68 0
Python string ascii_letters 260 0
Python string ascii_lowercase 116 0
Python string ascii_uppercase 121 0
How to Create Download Manager in Python 394 0
Python random weibullvariate 150 0
python random paretovariate 121 0
Python random vonmisesvariate 151 0
Python random normalvariate 158 0
Python random lognormvariate 102 0
Python random gauss 104 0
Python random gammavariate 112 0
Python random expovariate 165 0
Python random betavariate 148 0
Python random triangular 103 0
Python random uniform 129 0
Python random random 108 0
Python random sample 160 0
Python random shuffle 168 0
Python random choices 189 0
Python random choice 151 0
Python random randint 134 0
Python random randrange 182 0
Python random getrandbits 127 0
Python random setstate 121 0
Python random getstate 160 0
Python random seed 158 1
Python random Introduction 159 0

Comments