## Chapter 7, Lesson 4 Text

## Lesson Four: The Math Library

Mathematics 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 **import**statement after using the **pdb**, **datetime** 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 Function | Description | Example |
---|---|---|

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 tuple | math.fsum([1,3,2]) returns 6.0 |

math.pow(X,Y) | Returns X raised to the Y power | math.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.0math.cos(0) returns 1.0math.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.0math.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

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-known**, **constant** (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 Constant | Description | Value |
---|---|---|

math.pi | Mathematical "Pi" representing the ratio of a circle's circumference to its diameter | 3.14159... |

math.e | Mathematical "e", representing the base of the natural logarithm | 2.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

### 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 Function | Description | Value |
---|---|---|

round(X) | Returns the nearest integer to "X" | round(3.2) returns 3round(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 tuple | max(1,10) returns 10max([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 tuple | min(1,10) returns 1min([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

### 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

mathmodule, set up the originaltempsarray, and also initializenumTempsto contain the number of elements in thetempslist. To calculate anaveragevalue, you mustsumup 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 thetempslist. 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.

- Inside the "
for" loop (already provided for you)

- Initialize the variable
rawValueto the value in thetempsarray at the "i" index position.- Initialize a variable named
intValueto contain an integer formed by dropping the fractional part fromrawValue. Whichmathlibrary function should you use for this task?- Store the
intValueback into thetempsarray at the same "i" index position.- After the "
for" loop, print the updatedtempslist to the screen.- Next, find and print the minimum value from the
tempslist (e.g. "min = <minimum>"). Use a core function to find the minimum.- Next, find and print the maximum value from the
tempslist (e.g. "max = <maximum>"). Use a core function to find the maximum.- Next, initialize a variable named
averageby finding the sum of all items in thetempslist and then dividing by the number of items in the list (numTemps). Whichmathlibrary function should you use to find the sum?- Finally, the last
averageto the screen with 2 decimal digits of precision.

Try It Now

import math# original temperature listtemps = [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 listfor 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 valueprint(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.85If you change some of the starting temperatures, the calculated minimum, maximum and average values should change accordingly.