Chapter 7, Lesson 4 Text

Lesson Four: The Math Library

 

Math formulas inside a heartMathematics is full of interesting functions and constants that you might have trouble remembering or coding on your own. Fortunately, Python contains a math module that supports many of these concepts for you. It is much easier to use pre-built functions to perform these tasks instead of re-inventing the code on your own.

Using the "math" Module

To access the per-built mathematic functions, you will first need to import the math module at the top of your code. You should be familiar with the importstatement after using the pdbdatetime and random libraries in earlier lessons.

import math

Just like the random library, the math module contains a long list of functions that you can call directly, without creating any new object or variable. Simply start with the module name, math, then a dot (.), and then the function name with any required parameters in parentheses.

Common Math Functions

The following table describes some common math module functions. If you haven’t learned about some of these math concepts in your math class yet, that’s OK.  You only need to use these in a program if you have a good reason and understand what the functions mean.

Math FunctionDescriptionExample
math.ceil(X)Returns the lowest integer greater than or equal to X (meaning, always round fractional parts up to the next integer)math.ceil(3.2) returns 4
math.fabs(X)Returns the absolute value of X (removes any negative sign)math.fabs(-12) returns 12.0
math.factorial(X)Returns the factorial of X (which must be positive or zero)math.factorial(5) returns 120
math.floor(X)Returns the highest integer less than or equal to X (meaning, round down or truncate any fractional part)math.floor(3.2) returns 3
math.fsum(X)Returns the sum of adding together all of the elements in the input list or tuplemath.fsum([1,3,2]) returns 6.0
math.pow(X,Y)Returns X raised to the Y powermath.pow(2,3) returns 8.0
math.sqrt(X)Returns the square root of X (which must be positive!)math.sqrt(3) returns 1.7320508
math.sin(X)
math.cos(X)
math.tan(X)
Returns the trigonometric sine, cosine, or tangent of the input angle X (where X is in radians)math.sin(0) returns 0.0
math.cos(0) returns 1.0
math.tan(0) returns 0.0
math.degrees(X)
math.radians(X)
Given an input angle X in radians or degrees, returns the same angle in the other measurement system (degrees or radians)math.degrees(math.pi / 2) returns 90.0
math.radians(90) returns 1.570796

 

Let's double-check these expected results with some live code. Run the examples below and confirm that each output matches the function's purpose.

Try It Now

import math
print("ceil(3.2) = ",math.ceil(3.2))
print("fabs(-12) = ",math.fabs(-12))
print("factorial(5) = ",math.factorial(5))
print("floor(3.2) = ",math.floor(3.2))
print("fsum([1,2,3]) = ",math.fsum([1,2,3]))
print("pow(2,3) = ",math.pow(2,3))
print("sqrt(3) = ",math.sqrt(3))
print("sin(0) = ",math.sin(0))
print("cos(0) = ",math.cos(0))
print("tan(0) = ",math.tan(0))
print("degrees(math.pi / 2) = ",math.degrees(math.pi / 2))
print("radians(90) = ",math.radians(90))

In some cases, you will see that a decimal value (e.g. 8.0) is returned, while in other cases an integer (e.g. 4) is produced. You can usually tell from the function description what kind of output will be expected. Some functions, like ceil() or floor(), intentionally find and return integers, while others like sqrt() will by definition produce decimal or floating point values.

Note that we have used "math.pi" on one of the lines. "Pi" (or the Greek letter "π") is a well-known numerical value that represents the radio of a circle's circumference (distance around) to the circles diameter (distance across). We'll talk more about mathematical constant next!

Common Math Constants

Mathematics is filled with well-knownconstant (un-changing) values like "Pi" that have special meaning or uses in other formulas. These values are often very long floating point numbers that are not easy to remember or write out. The Python math library contains definitions for these values so you don't have to re-create them on your own. Simply write "math", then a dot (.), and then the constant name any place where you'd normally enter a hard-coded number like 1.0 or 5.3.

The following table shows the math module constants that you can use.

Math ConstantDescriptionValue
math.piMathematical "Pi" representing the ratio of a circle's circumference to its diameter3.14159...
math.eMathematical "e", representing the base of the natural logarithm2.71828...

 

Recent versions of Python also include constants for concepts like "infinity" (math.inf) or "not-a-number" (math.nan). These constants might be used in scientific or engineering applications, but you are unlikely to need them yourself in most common programs.

Let's use one of these constants for something practical. If you've taken a geometry class, you know that the area of a circle can be calculated as 2 times "Pi" times the radius of the circle. In Python code, given a variable named radius, we could write this equation as shown below.

area = 2 * math.pi * radius

The code below defines a starting radius and then calculates and prints the area. Try it yourself, substituting some different values for the radius.

Try It Now

import math
radius = 5.0
area = 2 * math.pi * radius
print(str.format("Area of a circle with radius {} = {:.2f}",radius,area))

Core Math Functions

There are a small number of math-related functions that are built into the core Python library. That means you don't need to import the math module or write "math." on the front of them! Simply call the functions directly, as described in the table below.

Core FunctionDescriptionValue
round(X)Returns the nearest integer to "X"round(3.2) returns 3
round(3.7) returns 4
max(X,Y)
max(<list or tuple>)
Returns the largest value of X, Y or that is found in the input list or tuplemax(1,10) returns 10
max([1,3,6]) returns 6
min(X,Y)
min(<list or tuple>)
Returns the smallest value of X, Y or that is found in the input list or tuplemin(1,10) returns 1
min([1,3,6]) returns 1
sum(<list or tuple>)Adds together all of the elements in the input list or tuple (like math.fsum())sum([1,3,6]) returns 10

 

Give these functions a try for yourself using the sample code below.

Try It Now

print("round(3.2) = ",round(3.2))
print("round(3.7) = ",round(3.7))
print("max(1,10) = ",max(1,10))
print("max([1,3,6]) = ",max([1,3,6]))
print("min(1,10) = ",min(1,10))
print("min([1,3,6]) = ",min([1,3,6]))
print("sum([1,3,6]) = ",sum([1,3,6]))

 

Further Reading

If you would like to explore some of the more advanced math module features, click on the link below to view the official Python documentation.

https://docs.python.org/3/library/math.html

 

Work with Me: Temperature Monitoring

 

Imagine that you work with a weather-monitoring organization, and you are presented with a list of 12 temperature readings taken over a single day. Each value in the list initially appears as a decimal number on the Fahrenheit scale (e.g. 86.35 degrees).

temps = [50.35, 51.75, 53.08, 57.00, 59.25, 61.19, 65.10, 64.22, 58.35, 55.98, 53.50, 50.95, 50.00]

Your job is to process these temperatures as follows:

  • Convert each value in the list to an integer by dropping any fractional part, and updating the list element
  • Print the list of rounded values
  • Find and print the minimum temperature
  • Find and print the maximum temperature
  • Find and print the average temperature

The starter code below will import the math module, set up the original temps array, and also initialize numTemps to contain the number of elements in the temps list. To calculate an average value, you must sum up all of the items in the list, and then divide by the number of items in the list.

The starter code also sets up a "for" loop that will iterate over each item in the temps list. Because we want to update each item in the list, we are setting up an index value "i" that will range over all of the valid list elements (0 through 11). You are going to use that index value to read a value from the list, drop the fractional part, and then store the new integer back into the list at that same spot. Remember that individual list elements can be read and set by using an index number in square brackets (e.g. temps[i]).

Complete the program by following the steps below.

  1. Inside the "for" loop (already provided for you)
    1. Initialize the variable rawValue to the value in the temps array at the "i" index position.
    2. Initialize a variable named intValue to contain an integer formed by dropping the fractional part from rawValue. Which math library function should you use for this task?
    3. Store the intValue back into the temps array at the same "i" index position.
  2. After the "for" loop, print the updated temps list to the screen.
  3. Next, find and print the minimum value from the temps list (e.g. "min = <minimum>"). Use a core function to find the minimum.
  4. Next, find and print the maximum value from the temps list (e.g. "max = <maximum>"). Use a core function to find the maximum.
  5. Next, initialize a variable named average by finding the sum of all items in the temps list and then dividing by the number of items in the list (numTemps). Which math library function should you use to find the sum?
  6. Finally, the last print() statement (already provided for you) will display the average to the screen with 2 decimal digits of precision.

 

Try It Now

import math
# original temperature list
temps = [50.35, 51.75, 53.08, 57.00, 59.25, 61.19, 65.10, 64.22, 58.35, 55.98, 53.50, 50.95, 50.00]
numTemps = len(temps) # get the number of entries in the list
for i in range(0,numTemps): # loop over each list index value
# get original value at this list spot
# truncate the fractional part
# store integer value back in this list spot
# print updated temps list, min temp value and max temp value
# calculate and display the average list value
print(str.format("average = {:.2f}",average))
 
  

Console

Given the original temperature list, your program should produce output like the example below.

temps =  [50, 51, 53, 57, 59, 61, 65, 64, 58, 55, 53, 50, 50]
min   =  50
max   =  65
average = 55.85

If you change some of the starting temperatures, the calculated minimum, maximum and average values should change accordingly.


Last modified: Sunday, 18 August 2019, 9:37 PM