Mathematics in Python

1. More Math

In natural resource management and research we do a lot of arithmetic (and stats and geometry, and trig, and some calculus) so we want to have a good grasp on how to work with numbers in Python. Below are some of the most common math operators we'll use in our work. This is not a full set, just the ones we use the most. Try these functions printing the results out to make sure they do what you expect.

x + y Add x and y
x - y Subtract y from x
x * y Multiply x times y
x / y Divide x by y
x ** y Returns x raised to the power of y
x % y The remainder of x divided by y. Also known as the modulus
x // y Returns the integral portion of x divided by y
-x Negative of x
abs(x) Absolute value of x


2. Mathematical Functions

Python comes with a package for common mathematical functions. There are also a number of extensions and packages for Python that provide access to a huge variety of capabilities for doing mathematics, statistics, and even spatial statistics. To use these functions you will need to "import" the math library.

Import packages by putting the line "import package" where "package" is the name of the package you want to import, at the top of your script file. In this case you'll want to add "import math".

You can use math functions to set a variable to a new value. If you wanted to find the square root of 256, you could type:

import math

Below is table with the most commonly used mathematical functions.

math.e Exponent: The value of e
math.pi PI: The value of pi
math.exp(x) Exponential: e raised to the value of x
math.pow(x,y) Power Function: x raised to the value of y
int(x) Integer: converts x to an integer
round(x,d) Round: rounds x to the number of digits, d if d is negative, otherwise rounds x to the number of fractional digits d
math.degrees(r) Converts a radian value to degrees
math.radians(d) Converts degrees to radians
math.sin(x) Returns the trigonometric sine (length of the opposite side of a right triangle over the hypotenuse) of the angle x in radians
math.cos(x) Returns the cosine (length of the adjacent side of a right triangle over the hypotenuse) of the angle x in radians
math.tan(x) Returns the tangent (length of the opposite side of a right triangle over adjacent side) of the angle x in radians
math.asin(x) Returns the inverse or "arc" sine for the length x
math.acos(x) Returns the inverse or "arc" cosine for the length x
math.atan(x) Returns the inverse or "arc" tangent for the length x
math.sqrt(x) Returns the square root of x
math.isinf(x) Returns true if the value of x is infinity, false otherwise
math.isnan(x) Returns true, if the value of x is "Not a Number" (NaN), false otherwise


The last two functions help with special situations with computer-based numbers. If you accidentally divide a value by 0 the result will be infinite. Python can represent this and the "isinf()" function will detect that the value is infinity (or negative inifinity). The value of 0/0 is not defined and is therefore, "not-a-number" or "nan". The last function will test for this case.

4. Converting Direction and Distance to Coordinates

Lets put some of this math to good use. Another common task is converting distance and direction measurements to UTM coordinates.  We start with an existing Easting, and Northing which are labeled Easting1 and Northing1 in the diagram below. The bearing, also known as an azimuth, is measured as the angle from north in the clockwise direction. The distance is measured from the Easting1, Northing1 to our new coordinate, Easting2, Northing2 in the direction of the bearing. The problem is to find the change in the easting (ΔEasting) and then add this to the original easting (Easting1) to find the new easting (Easting2). We then repeat this for the northing. The equations for this are:

Illustration of SOHCAHTOA

To do this, we need to find the ΔEasting and ΔNorthing values. This requires a bit of trig. Remember SOHCAHTOA? This is the most important word in trig as it tells us which sides of our triangle can be found with sine and cosine functions. Using the diagram on the right, we read SOHCAHTOA as:

"Opposite" refers to the side of the triangle that is opposite the angle while "Adjacent" refers to the side that is next to the Angle. Converting the word "Over" to a divide symbol and using functions for the Sine and Cosine gives us:

Diagram showing the relationship between distance and bearing to change in northing and easting

Using the standard GIS terminology in our diagram on the right, we get:

Multiplying both sides by Distance gives us:

Note that the Bearing needs to be in radians for the Sin and Cos functions and GIS folks us degrees. The conversion below will convert a standard bearing to radians:

We need to be making these calculations in a projected system rather than geographic so we are using easting's for "x" and northing's for "y". To to the same conversion in geographic requires different math.


The data below are an actual sample taken from the 1992 Global Change Project for Rocky Mountain National Park. 





Bearing (aka Azimuth)































Data from the Global Change project.  The species code 108 indicates lodge pole pine and 113 indicates limber pine.  The Diameter at Breast Height (DBH) is in centimeters, the distance is in meters, and the Bearing is in degrees.

We need to convert these data into coordinates for each tree.  The original Easting is 446131 and the Northing is 4475364, for the south-west corner of the plot.  The plot is in Rocky Mountain National Park, which is in Zone 13 in Colorado.  The code below will convert the distance and azimuth to a change in x,y and then add them to the coordinate at the corner of the plot to find a coordinate for one of the points:

 import math

 DeltaEasting = math.sin(BearingInRadians) * Distance
 DeltaNorthing = math.cos(BearingInRadians) * Distance
 Easting2 = Easting1 + DeltaEasting
 Northing2 = Northing1 + DeltaNorthing

Type in the code above and try it with different values from the table. Obviously, this is not the most efficient way to convert data. In just a bit we'll learn to read data from a file, perform operations on the data, and then write it back out to another file. This will allow you to perform very complex mathematical conversions on very large (millions of points) data sets.

5. Precedence

There are tightly defined rules for how any mathematical equation is evaluated in Python.  The following two functions will produce the same result, 31.

x = 3 * 10 + 1
x = 1 + 3 * 10

This is because multiplications are performed first, then additions.  This can cause serious confusion.  The easy solution is to add parenthesis wherever there is the possibility of confusion.  This will give two new functions:

 x = (3 * 10) + 1 = 31 (30 plus 1)
 x = 3 * (10 + 1) = 33 (3 times 11)

6. Complex Values

Python handles complex values as a built in type and many of the functions will accept complex values. See the Python Documentation at the end of this section.

You can create complex values by appending "J" to the end of the value. The value will be the imaginary part and the real part will be 0. You can access the portions of the values with z.real and z.imag where "z" is the complex variable.

Additional Resources

Python Documentation

© Copyright 2018 HSU - All rights reserved.