Chapter 7: Using existing functions

The math module

face Josiah Wang

The official documentation for the math module contains a list of functions and variables defined for the module.

Take a quick glance at them, and then try to answer/solve the following problems.

Please try to solve them yourself before peeking at the sample solutions! You will learn better this way!

1 2 3 4

Question 1

Given p = 0.7 and q = 0.3, use Python to compute the value of -p \times log_2(p)-q \times log_2(q)

Sample solution:

Here are two possible solutions. To compute log_2, you can either use math.log2(x) or the more generic math.log(x, base).

Tip: you are actually computing the entropy (which will be covered in your Introduction to Machine Learning course)

import math
p = 0.7
q = 0.3
entropy = -p*math.log2(p) - q*math.log2(q)
print(entropy)
import math
p = 0.7
q = 0.3
entropy = -p*math.log(p, 2) - q*math.log(q, 2)
print(entropy)

Question 2

Compute the sigmoid of 0.6 using Python, where sigmoid(x) is defined as \frac{1}{1 + e^{-x}}.

Sample solution:

Here is a possible solution.

import math
sigmoid = 1 / (1+math.exp(-0.6))
print(sigmoid)

Question 3

Write Python code to compute the cosine of 45 degrees. Use Python to convert 45 degrees to radians if needed.

Sample solution:

Here are two possible implementations. The first is at a higher-level of abstraction, by making use of the math.radians() function. The second is more low level and computes the radians directly (and abstracting the value of \pi with math.pi instead).

import math
x_deg = 45
x_rad = math.radians(x_deg)
cos_x = math.cos(x_rad)
print(cos_x)
import math
x_deg = 45
x_rad = x_deg / 180 * math.pi
cos_x = math.cos(x_rad)
print(cos_x)

Question 4

How do you represent negative infinity in Python?

Sample solution:

Here are several ways to represent negative infinity in Python.

>>> import math
>>> -math.inf
-inf
>>> -float("inf")
-inf
>>> float("-inf")
-inf