When programming, whether it is for statistical analysis of for experimental design we will be doing a lot of mathematical operations. For example, in the console type:
2 + 2
Python will compute the answer for you and output it onto the screen.
2 + 2
Python will compute the answer for you and output it onto the screen.
Python has 7 basic arithmetic operators:
4 + 2 = 6
Addition
4 - 2 = 2
Subtraction
4 * 2 = 8
Multiplication
4 / 2 = 2
Division
4 ** 2 = 16
Exponent
4 % 2 = 0
Modulus (computes the remainder in a division)
4 // 2 = 2
Floor Division (computes a division, then drops anything after the decimal)
These are useful, but what if we want to do some more sophisticated math, like logarithms and trigonometry?
4 + 2 = 6
Addition
4 - 2 = 2
Subtraction
4 * 2 = 8
Multiplication
4 / 2 = 2
Division
4 ** 2 = 16
Exponent
4 % 2 = 0
Modulus (computes the remainder in a division)
4 // 2 = 2
Floor Division (computes a division, then drops anything after the decimal)
These are useful, but what if we want to do some more sophisticated math, like logarithms and trigonometry?
Modules
A module in Python is a file that has a specific functionality. In our case, we are looking for more robust math operations. Python comes with a module called math which provides exactly what we need. To get access to the operations inside math, we have to include it in our environment.
Type import math into the console to bring in the math module. Now, we can use anything provided by math in our programming!
Try out a few of these functions from the math module by typing the following into the console:
math.exp(4)
Computes e to the power of 4.
math.log(4)
Computes the natural logarithm of 4.
math.sqrt(4)
Computes the square root of 4.
Type import math into the console to bring in the math module. Now, we can use anything provided by math in our programming!
Try out a few of these functions from the math module by typing the following into the console:
math.exp(4)
Computes e to the power of 4.
math.log(4)
Computes the natural logarithm of 4.
math.sqrt(4)
Computes the square root of 4.
The math module is full of useful mathematical operators. The documentation provides a list of all of them here: https://docs.python.org/3.8/library/math.html
We will be using modules all the time to make our programming lives easier. They allow us to use the power of Python without writing all of the code from scratch.
Let's move on to the next tutorial to learn how to use variables in Python.
We will be using modules all the time to make our programming lives easier. They allow us to use the power of Python without writing all of the code from scratch.
Let's move on to the next tutorial to learn how to use variables in Python.