Masthead
Header

Mathematics in Python

In Review

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
y=math.sqrt(256)

Below is table with the most commonly used mathematical functions.

Constants  
math.e Exponent: The value of e
math.pi PI: The value of pi
Exponential  
math.exp(x) Exponential: e raised to the value of x
math.pow(x,y) Power Function: x raised to the value of y
Conversions  
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
Trigonometric  
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
Other  
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.

3.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.  The data below are an actual sample taken from the 1992 Global Change Project for Rocky Mountain National Park. 

Tree

Species

DBH

Distance

Azimuth

1

108

23.1

13.9

1

10

108

27.1

16.2

6

20

113

4.2

13.4

33

30

108

23

6

46

40

108

12.1

17.4

57

50

113

15.9

7.9

76

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 Azimuth 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
 
 CornerEasting=446131
 CornerNorthing=4475364
 
 Azimuth=1
 Distance=13.9
 
 DistanceEast = math.sin(Azimuth) * Distance
 DistanceNorth = math.cos(Azimuth) * Distance
 
 PointEasting= CornerEasting + DistanceEast
 PointNorthing= CornerNorthing + DistanceNorth
 
 print(PointEasting)
 print(PointNorthing)

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.

4. 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)

5. 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