Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

3 Basic Mathematical Operations

3.1Lesson goals

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.

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):

OperationResultNumeric class compatibility
x + ySum of x and y (addition)int, float, complex
x - yDifference of x and y (subtraction)int, float, complex
x * yProduct of x and y (multiplication)int, float, complex
x / yQuotient of x and y (division)int, float, complex
x // yInteger quotient of x and y (integer division)int, float
x % yRemainder of x / yint, float
divmod(x, y)Provides a tuple with the format of (x // y, x % y)int, float
-xNegative of xint, float, complex
+xLeave x unchangedint, float, complex
abs(x)Absolute value of xint, float, complex
int(x)Cast x as an integerint, float
float(x)Cast x as a floating pointint, float
complex(x, y)Creates complex number x + yj where x is the real part and y is the imaginary partint, float
x.conjugate()Conjugate of the complex number xcomplex
pow(x, y)Raises the number x to the power yint, float, complex
x ** yRaises 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 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 7.9 g/cm37.9 \text{ g} / \text{cm}^3 into units of lb/in3\text{lb} / \text{in}^3. Recall that 1 g=0.0022 lb1 \text{ g} = 0.0022 \text{ lb} and 1 cm3=0.061 in31 \text{ cm}^3 = 0.061 \text{ in}^3. Report the converted density to the using the print() function.


Solution:

We use unit conversion to convert our density’s unit basis from  g/cm3\text{ g} / \text{cm}^3 to lb/in3\text{lb} / \text{in}^3. Mathematically this looks like,

7.9 gcm31 cm30.061 in30.0022 lb1 g=0.29 lbin37.9 \text{ } \frac{\text{g}}{\text{cm}^3} \cdot \frac{1 \text{ cm}^3}{0.061 \text{ in}^3} \cdot \frac{0.0022 \text{ lb}}{1 \text{ g}} = 0.29 \text{ } \frac{\text{lb}}{\text{in}^3}

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 xx to the power of yy (i.e., xyx^y ). 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 2.4 cm2.4 \text{ cm} and a length of 12.1 cm12.1 \text{ cm}. Recall that the volume of a cylinder is,

V=πr2LV = \pi r^2 L

where VV is the volume, rr is the radius, and LL is the length. For this calculation approximate π\pi as 3.14 3.14 .


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.


Representing numbers in Python using scientific notation (i.e., m10nm \cdot 10^n, where mm is the significand and nn is the exponent) is done by using either the e or E characters to represent the term 10 \cdot 10. This formatting style is especially useful when typing out large or small numbers. For example, it is much faster to type out 120 120 million as 1.21081.2 \cdot 10^8 than 120,000,000120,000,000. 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,

v=λνv = \lambda \nu

where vv is the wave’s velocity (i.e., its speed, unit:  m/s\text{ m}/ \text{s}), λ\lambda is it wavelength (unit: m\text{m}), and ν\nu is its frequency (unit: 1/s=Hz1/\text{s} = \text{Hz}).

Calculate the frequency of a wavefront of light that is traveling in a vacuum that has a wavelength of 550 nm550 \text{ nm}. Recall that the speed of a light wave traveling in a vacuum is 3.0108 m/s3.0 \cdot 10^8 \text{ m}/ \text{s}.


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 1 nm=1109 m1 \text{ nm} = 1 \cdot 10^{-9} \text{ m}. Mathematically the calculation is,

3.0108 ms550109 m=5.451014 Hz\frac{3.0 \cdot 10^8 \text{ } \frac{\text{m}}{\text{s}}}{550 \cdot 10^{-9} \text{ m}} = 5.45 \cdot 10^{14} \text{ Hz}

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 5.451014 Hz=545 THz5.45 \cdot 10^{14} \text{ Hz} = 545 \text{ THz}.


Python can round the number xx to a desired precision level using the round() function. This function accepts two arguments:

  1. The number to be rounded, x

  2. The rounding precision level AFTER the decimal point, ndigits. This precision level can be either positive or negative and by default ndigits=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,

PV=nRTPV = nRT

where PP is the pressure, VV is the volume the gas resides in, nn is the number of gas particles, TT is the temperature of the gas, and RR is called the ideal gas constant.

Calculate the moles (unit: mol\text{mol}) of Ar atoms needed to fill a 2.2 m32.2 \text{ m}^3 vessel to 0.2 MPa0.2 \text{ MPa} of pressure at 23 oC=297 K23 \text{ }^\text{o}\text{C} = 297 \text{ K}. For this problem, use the ideal gas constant in the form of 8.3145 m3 Pamol1K1 8.3145 \text{ m}^3 \cdot \text{ Pa} \cdot \text{mol}^{-1} \cdot \text{K}^{-1} to keep the number of unit conversions to a minimum. Recall that the mole (unit: mol\text{mol}) 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,

(0.2106 Pa)(2.2 m3)(8.3145 m3PamolK)(297 K)=178.18 mol\frac{(0.2 \cdot 10^6 \text{ Pa}) \cdot (2.2 \text{ m}^3)}{(8.3145 \ \frac{\text{m}^3 \cdot \text{Pa}}{\text{mol} \cdot \text{K}})(297 \text{ K})} = 178.18 \text{ mol}

Notice the use of Pa\text{Pa} instead of MPa\text{MPa} for pressure units and K\text{K} 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!