3 Basic Mathematical Operations
3.1Lesson goals¶
Learn how to implement basic mathematical operations using built-in Python commands.
Represent large and small numbers using scientific notation.
Utilize the built-in
round()function to manage significant figures (i.e., sig figs) when displaying numbers.
3.2Overview¶
Python is a popular programming language for scientific and engineering applications. As one would expect, this requires Python to be able to perform mathematical operations. Python comes equipped to handle many of the basic, but important mathematical operations within its built-in “standard” code library. This lesson will teach you how to implement many of these basic mathematical operations so you can start calculating numbers for your numerical analysis needs.
3.3Built-in mathematical operations¶
The Python standard library comes equipped with a
set of useful mathematical operations
for the int, float, and complex classes (table taken from above link):
| Operation | Result | Numeric class compatibility |
|---|---|---|
x + y | Sum of x and y (addition) | int, float, complex |
x - y | Difference of x and y (subtraction) | int, float, complex |
x * y | Product of x and y (multiplication) | int, float, complex |
x / y | Quotient of x and y (division) | int, float, complex |
x // y | Integer quotient of x and y (integer division) | int, float |
x % y | Remainder of x / y | int, float |
divmod(x, y) | Provides a tuple with the format of (x // y, x % y) | int, float |
-x | Negative of x | int, float, complex |
+x | Leave x unchanged | int, float, complex |
abs(x) | Absolute value of x | int, float, complex |
int(x) | Cast x as an integer | int, float |
float(x) | Cast x as a floating point | int, float |
complex(x, y) | Creates complex number x + yj where x is the real part and y is the imaginary part | int, float |
x.conjugate() | Conjugate of the complex number x | complex |
pow(x, y) | Raises the number x to the power y | int, float, complex |
x ** y | Raises the number x to the power y, equivalent to pow(x, y) | int, float, complex |
round(x, ndigits) | Rounds x to precision level set by ndigits (default is None) | int, float |
As seen in the table, there are operations for addition, subtraction, multiplication, division, and more. Many of
these operations apply to all three numeric classes that we have covered so far (i.e., int,
float, and complex), but some operations are exclusive to only one or two classes.
Python follows the standard order of mathematical operations (e.g., operations occur from left to right, multiplication
and division before addition and subtraction). Let’s spend the rest of this lesson going through each operation in more
detail. In all following cases, treat the variables x and y as being part of a numeric data class.
3.4Addition¶
The addition / summation of numbers is handled using the + operator and is written out using the command x + y,
where x and y are the two numbers to be summed. Python can perform this operation on all three numeric classes.
The block of code below provides four examples of adding two or more numbers:
# Addition examples
sum_int = 1 + 4
sum_float = 125.3 + 235.6
sum_complex = (2.4 + 2.5j) + (1.0 + 0.5j)
sum_mix = 10 + 4.2 + 2.5
print(sum_int)
print(sum_float)
print(sum_complex)
print(sum_mix)5
360.9
(3.4+3j)
16.7
3.5Subtraction¶
The subtraction / difference of numbers is handled using the - operator. Similar to addition, Python can perform this
operation on all three numeric classes. The block of code below provides four examples of subtracting two or more
numbers:
# Subtraction examples
diff_int = 1 - 4
diff_float = 125.3 - 235.6
diff_complex = (2.4 + 2.5j) - (1.0 + 0.5j)
diff_mix = 10 - 4.2 - 2.5
print(diff_int)
print(diff_float)
print(diff_complex)
print(diff_mix)-3
-110.3
(1.4+2j)
3.3
3.6Multiplication¶
The multiplication of numbers to obtain a product is handled using the * operator. Similar to addition and
subtraction, Python can perform this operation between all three numeric classes with the command structure x * y.
Below are four examples of multiplying two numbers together:
# Multiplication examples
product_int = 1 * 4
product_float = 125.3 * 235.6
product_complex = (2.4 + 2.5j) * (1.0 + 0.5j)
print(product_int)
print(product_float)
print(product_complex)4
29520.68
(1.15+3.7j)
3.6.1Division¶
There are three division-based mathematical operations in the Python standard library:
The
/operator obtains the quotient between two numbers. This operator works on all three numeric data types.The
//operator performs integer-based division. This operator only works withintandfloatclasses.The
%operator provides the remainder of an integer-based division operation. This also only works withintandfloatclasses
The divmod() function is a one-step route to get the
results from integer division and remainder operations simultaneously. The overall format of this function is
divmod(x, y) where x is the numerator and y is the denominator. The output is an object from the tuple data
class (we will cover what is a tuple in the next lesson) that has the format of ( x // y, x % y). Examples of the
three methods and divmod() are below:
# Division examples
x = 5.0
y = 2.0
print(x / y)
print(x // y)
print(x % y)
print(divmod(x, y))2.5
2.0
1.0
(2.0, 1.0)
3.6.2Example: Unit conversion¶
Convert the density into units of . Recall that
and . Report the converted density to the
using the print() function.
Solution:
We use unit conversion to convert our density’s unit basis from to . Mathematically this looks like,
The equivalent Python code is:
density = 7.9
convert = density * (0.0022 / 0.061)
print(convert)0.28491803278688527
This example demonstrates both how to use the / operator for floating point division and that multiple mathematical
operations can be chained together.
3.7Negated, unchanged, and absolute value¶
To quickly take the negative of a number, one places the - operator just before typing a variable (e.g., the
negative of x is -x). Conversely, the + operator just before a variable leaves that variable unchanged (e.g., +x
is x). While using +x instead of x seems somewhat excessive, the use of -x is a useful command rather than
issuing -1 * x. The block of code below uses the x and y variables from before, but now with the negated and
unchanged operators:
x = 2.5
print(x)
print(-x)
print(+x)2.5
-2.5
2.5
The abs() function calculates the absolute value of a number.
This function takes the form of abs(x), where x is the number that we want to know its absolute value. Below is a block of code that outputs the absolute value for our previously defined x and y variables:
x = -5.3
y = -13
z = 265.82
print(abs(x))
print(abs(y))
print(abs(z))5.3
13
265.82
3.8int and float casting¶
The last lesson discussed the concept of casting, which is the process of changing an object’s class
to another class. Casting variables into either int or a float objects are handled using the int() and float()
functions, respectively. The code below demonstrates how these two functions can be used to cast our current
variables x and y (an int and float object, respectively) into the other class:
x = -5.3
y = -13
print(int(x))
print(float(y))-5
-13.0
3.9Complex number operations¶
As we have already discussed, a complex object can be created two ways: it can be directly
typed out directly in the interactive shell or by issuing the complex() function. The conjugate of a complex number
can be found by running the .conjugate() method, which is a special function associated with the complex class.
We will discuss the concept of methods in later lessons, but for now all you need to know is that
methods are issued in a special way by first typing out the variable name, followed by the . symbol, then the
function’s name.
The example below first has the complex variable named position created using the complex() function. Next, a new
variable called position_complex is created, which represents the complex conjugate of position. Therefore, the
.conjugate() method is issued on position using the command position.conjugate(). All of this is detailed in
the block of code below:
position = complex(5.2, 2.6)
print(position)
position_conjugate = position.conjugate()
print(position_conjugate)(5.2+2.6j)
(5.2-2.6j)
3.9.1Power raising¶
The Python standard library provides two routes to raise the number to the power of (i.e., ). The first
route is to use the pow() function that accepts two input
arguments: (1) the base number x and (2) the power value y. The overall functional form is pow(x, y). All three
numeric classes are compatible with pow(). The code below shows two examples of using pow() with int and float
objects:
base_int = 2
exponent_int = 3
power_int = pow(base_int, exponent_int)
base_float = 25.2
exponent_float = 0.5
power_float = pow(base_float, exponent_float)
print(power_int)
print(power_float)8
5.019960159204453
The second route is through the use of the ** operator and takes the form of x ** y. This is equivalent to using
the pow() function but now done directly with an operator. The block of code below repeats the example above but now
using the ** operator:
print(base_int ** exponent_int)
print(base_float ** exponent_float)8
5.019960159204453
3.9.2Example: Volume of a cylinder¶
Calculate the volume of a cylinder that has a radius of and a length of . Recall that the volume of a cylinder is,
where is the volume, is the radius, and is the length. For this calculation approximate as .
Solution:
This example demonstrates the use of power raising when calculating floating point numbers. Here we will use the
** operator to square the radius.
radius = 2.4
length = 12.1
volume = (3.14) * (radius ** 2) * (length)
print(volume)218.84544
Equivalently, we could have used the pow(radius, 2) command to square the radius.
3.10Scientific notation¶
Representing numbers in Python using scientific notation
(i.e., , where is the significand and is the exponent) is done by using either the e or E
characters to represent the term . This formatting style is especially useful when typing out large or
small numbers. For example, it is much faster to type out million as than .
In Python this translates to:
number = 1.2E8
print(number)120000000.0
Notice that while the shell reads the number correctly, it outputs the number in a floating point style
notation. As we will see in a later lesson, Python offers numerous ways to display
numbers when cast to the str data type, including in scientific notation.
3.10.1Example: Math with large & small numbers¶
The velocity of a wave (e.g., sound, light, water) is related to its spatial wavelength and temporal frequency via the relationship,
where is the wave’s velocity (i.e., its speed, unit: ), is it wavelength (unit: ), and is its frequency (unit: ).
Calculate the frequency of a wavefront of light that is traveling in a vacuum that has a wavelength of . Recall that the speed of a light wave traveling in a vacuum is .
Solution:
This example highlights the usefulness of the E operator when entering both very large and small numbers into Python
code. The overall calculation is straightforward as we simply need to use the / operator and remember that
. Mathematically the calculation is,
The equivalent Python code is,
wavelength = 550E-9
velocity = 3.0E8
frequency = velocity / wavelength
print(frequency)545454545454545.44
Again, the returned number is a bit hard to read. As we become more proficient with Python, we will be able to display numbers in more human-readable fashion. The calculation though is correct as we get .
3.11Rounding¶
Python can round the number to a desired precision level using the
round() function. This function accepts two arguments:
The number to be rounded,
xThe rounding precision level AFTER the decimal point,
ndigits. This precision level can be either positive or negative and by defaultndigits=0.
The overall format of this function is round(x , ndigits=value), where value is the precision level. The code below demonstrates how round() is used to round the number 6832.36043 to various precision levels:
x = 6832.36043
print(x)
print(round(x, 1))
print(round(x, ndigits=2))
print(round(x, ndigits=-2))6832.36043
6832.4
6832.36
6800.0
The previous examples use round() as part of print() function. You can also permanently change the digit precision
of value using round(). This is useful when you want to control the number of significant figures in a variable.
x = 6832.36043
print(x)
x = round(x, 2)
print(x)6832.36043
6832.36
Notice that we have “updated” x’s value by calling x in the round() function. Python allows for recursive use of
objects, which is very useful when modifying and object.
3.11.1Example: Keeping significant figures sane¶
The ideal gas law relates the number of gas particles (atoms or molecules) to the pressure, the temperature, and the volume of the gas via the equation,
where is the pressure, is the volume the gas resides in, is the number of gas particles, is the temperature of the gas, and is called the ideal gas constant.
Calculate the moles (unit: ) of Ar atoms needed to fill a vessel to of pressure at . For this problem, use the ideal gas constant in the form of to keep the number of unit conversions to a minimum. Recall that the mole (unit: ) is an SI unit for amount. Report the moles first without any rounding considerations and then after rounding to the hundredths position.
Solution:
The actual calculation setup should be familiar by now, and the new feature demonstrated here is utilizing the
round() function. Mathematically the calculation is,
Notice the use of instead of for pressure units and for temperature units to keep everything consistent with the form of the ideal gas constant that is provided. The equivalent Python code is:
pressure = 0.2E6
volume = 2.2
gas_constant = 8.3145
temperature = 297
mol = (pressure * volume) / (gas_constant * temperature)
print(mol)
print(round(mol, 2))178.18046563010182
178.18
We can see that the Python shell is storing mol with an excessive level of precision, much more than what we care
for. The round() function allows us to report the number of moles in an easier to read format.
3.12Final thoughts¶
This lesson covered many of the basic, but important, mathematical operations provided in the Python standard library.
These include operations such as addition, subtraction, multiplication, division, and ways to raise and
round numbers. You may have noticed however the absence of other important mathematical concepts like trigonometric
functions, exponential functions, and statistical operations. While Python’s standard library does not provide these
operations outright, additional libraries can be imported into Python to increase its usefulness as a scientific
language. For example, both the math and NumPy
libraries for Python provide many additional mathematical operations and the ability to create numbered arrays. We will
explore both of these libraries in later lessons after we introduce
how to import and create Python libraries. For now, happy calculating!