 Prev: Strings      |      Next: Booleans

# 'random' and 'math' modules¶

## random¶

• The module 'random' is imported when random numbers are needed. It is a 'built in' module (included in the Python standard library which is installed with the language) but nevertheless it must be imported.

• 'random' offers a number of helpful functions such as:

• random.seed(seednum): initializes the random number generator (if not used then seed is the current system time). Use of the same seednum reproduces the random number sequence
• random.randint(start, stop): returns a random integer in [start, stop]
• random.randrange(start, stop[,step]): returns a random elemen in [start, stop] with [step] beng optional
• random.shuffle(x): Shuffles the sequence x
In :
import random
random.seed(12345)
a = random.randint(1,10)
a

Out:
7
In :
b = random.randrange(1,20,2)
b

Out:
9

## math¶

• math module is also built in and should be imported. It provides access to a variety of mathematical functions and constants. The math module consists mostly of thin "wrappers" (code that calls in turn the 'wrapped' functions) around the platform C math library functions.
• Some of them:
• math.exp(x): returns e**x
• math.log(x[, base]): returns the natural logarithm of x (to base e or to a given base)
• math.pow(x, y): raise x to the power of y
• math.sqrt(x): returns the square root of x
• math.pi: The mathematical constant π = 3.141592...
• math.e: The mathematical constant e = 2.718281...
In :
import math

r = 1
circ = 2*math.pi*r
area = math.pi*pow(r,2)
vol = 4/3*math.pi*pow(r,3)
area, vol

Out:
(3.141592653589793, 4.1887902047863905)

#### Order of operations¶

• Recall the order of operations:
• exponents and roots
• multiplication and division

When in doubt use parentheses

In :
# An example with more complex operations

x = 5

# Calculating exp(x) by calling math.exp() function
res1 = math.exp(x)

# The exponential function may also be calculated as a Taylor series using also math.factorial()
res2 = 1+x/math.factorial(1)+x**2/math.factorial(2)+x**3/math.factorial(3)+\
x**4/math.factorial(4)+x**5/math.factorial(5)+x**6/math.factorial(6)+\
x**7/math.factorial(7)+x**8/math.factorial(8)+x**9/math.factorial(9)+\
x**10/math.factorial(10)
# Note the use of '\' above to separate one long logical codeline into many physical lines

# The results we get from the two methods are close enough but not similar
# Include more factors in the Taylor series to get a better approximation
res1, res2

Out:
(148.4131591025766, 147.60384850489015)
• Of course, the code for computing the Taylor series sum is not efficient. We should write an appropriate function to make the computation and we shall see this example in the function section.  . Free learning material