* Edit Jan 2021: I recently completed a YouTube video covering topics in this post:
In this lesson, we'll explore Python's ability to perform basic computations. Although Python is a fully-fledged programming language, the console can serve as a powerful calculator and interactive tool for exploring and analyzing data. To follow along with this lesson, you'll need an open Python console, so launch Spyder (or your other favorite Python IDE) and use its console.
We'll start by going over the basic mathematical operators built into Python:
In [1]:
# Use + for addition:
4 + 9
Out[1]:
In [2]:
# Use - for subtraction:
5 - 10
Out[2]:
In [3]:
# Use * for multiplication:
8 * 4
Out[3]:
In [4]:
# Use / for division:
100 / 3
Out[4]:
In [5]:
# Use // for floor division (division rounded down to the nearest whole number):
100 // 3
Out[5]:
In [6]:
# Use ** for exponentiation
2**4
Out[6]:
Math expressions in Python follow the normal order of operations so and / are executed before + and -, and * is executed before multiplication and division.
In [7]:
# These operations are executed in reverse order of appearance.
2+3*5**2
Out[7]:
You can use parentheses in your math expressions to ensure that operations are carried out on the correct order. Operations within parentheses are carried out before operations that are external to the parentheses, just like you'd expect.
In [8]:
# Now the addition comes first and the exponentiation comes last.
((2+3) * 5 )**2
Out[8]:
If you're new to programming, you may not be familiar with the modulus operator, but it is another common math symbol that returns the remainder you'd get when dividing two numbers. Use the percent symbol to take the modulus:
In [9]:
# Use % for modulus
100 % 30
Out[9]:
Take the absolute value of a number with the abs() function:
In [10]:
abs(-30)
Out[10]:
Beyond abs() and the built in symbolic operators, Python doesn't have many math functions available by default. Instead, many common math functions are contained in libraries you can load into your project as necessary. The "math" module contains many additional functions of interest. Let's import the math module and explore some if its functions:
In [11]:
import math # Load the math module
In [12]:
# math.log() takes the natural logarithm of its argument:
math.log(2.7182)
Out[12]:
In [13]:
# Add a second argument to specify the log base:
math.log(100, 10) # Take the log base 10 of 100
Out[13]:
In [14]:
math.log(64, 2) # Take the log base 2 of 64
Out[14]:
In [15]:
# math.exp() raises e to the power of its argument
math.exp(10)
Out[15]:
In [16]:
# If you ever need the constants e or pi you can use:
math.e # Get the constant e
Out[16]:
In [17]:
math.pi # Get the constant pi
Out[17]:
In [18]:
# Use math.sqrt() to take the square root of a number:
math.sqrt(64)
Out[18]:
In [19]:
# Use round() to round a number to the nearest whole number:
In [20]:
round(233.234)
Out[20]:
In [21]:
# Add a second argument to round to a specified decimal place
round(233.234, 1) # round to 1 decimal place
Out[21]:
In [22]:
# Enter a negative number to round to the left of the decimal
round(233.234, -1) # round to the 10's place
Out[22]:
In [23]:
# Round down to the nearest whole number with math.floor()
math.floor(2.8)
Out[23]:
In [24]:
# Round up with math.ciel()
math.ceil(2.2)
Out[24]:
Common trigonometric functions are also available in the math module. The trig functions assume your argument is expressed in terms of radians, not degrees.
In [25]:
math.cos(0) # Cosine
Out[25]:
In [26]:
math.sin(math.pi/2) # Sine
Out[26]:
In [27]:
math.tan(math.pi/4) # Tangent
Out[27]:
In [28]:
math.acos(1) # Inverse Cosine
Out[28]:
In [29]:
math.asin(1) # Inverse Sine
Out[29]:
In [30]:
math.atan(1) # Inverse Tangent
Out[30]:
Convert between radians and degrees with math.radians() and math.degrees():
In [31]:
math.radians(180) # Convert degrees to radians
Out[31]:
In [32]:
math.degrees(math.pi) # Convert radians to degrees
Out[32]:
Wrap Up
Any time you need to perform a common mathematical operation in Python, it is probably available in a library that is one import statement away. Python's Anaconda distribution comes with most of the libraries we'll use in this guide, but there many more that can extend Python's functionality even further. When in doubt, try Google. Helpful blog posts and answers posted on programming sites like stackoverflow can often save you a lot time and help you learn better ways of doing things.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.