Path: blob/master/12-Advanced Python Modules/03-Math-and-Random-Module.ipynb
666 views
Math and Random Modules
Python comes with a built in math module and random module. In this lecture we will give a brief tour of their capabilities. Usually you can simply look up the function call you are looking for in the online documentation.
We won't go through every function available in these modules since there are so many, but we will show some useful ones.
Useful Math Functions
Rounding Numbers
Mathematical Constants
Logarithmic Values
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-12-7563e0a48092> in <module>()
----> 1 math.log(0)
ValueError: math domain error
Custom Base
Trigonometrics Functions
Random Module
Random Module allows us to create random numbers. We can even set a seed to produce the same random set every time.
The explanation of how a computer attempts to generate random numbers is beyond the scope of this course since it involves higher level mathmatics. But if you are interested in this topic check out:
Understanding a seed
Setting a seed allows us to start from a seeded psuedorandom number generator, which means the same random numbers will show up in a series. Note, you need the seed to be in the same cell if your using jupyter to guarantee the same results each time. Getting a same set of random numbers can be important in situations where you will be trying different variations of functions and want to compare their performance on random values, but want to do it fairly (so you need the same set of random numbers each time).
Random Integers
Random with Sequences
Grab a random item from a list
Sample with Replacement
Take a sample size, allowing picking elements more than once. Imagine a bag of numbered lottery balls, you reach in to grab a random lotto ball, then after marking down the number, you place it back in the bag, then continue picking another one.
Sample without Replacement
Once an item has been randomly picked, it can't be picked again. Imagine a bag of numbered lottery balls, you reach in to grab a random lotto ball, then after marking down the number, you leave it out of the bag, then continue picking another one.
Shuffle a list
Note: This effects the object in place!
Random Distributions
Uniform Distribution
Final Note: If you find yourself using these libraries a lot, take a look at the NumPy library for Python, covers all these capabilities with extreme efficiency. We cover this library and a lot more in our data science and machine learning courses.