Velamuvi AIAcademy

Lesson 12 of 12 · Reading Maths

Maths in Python

Do maths in Python with confidence: the math and statistics modules, rounding and floating-point care, and a first look at NumPy arrays, the tool behind data science and AI.

  • 8 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • The tools in Python's math module
  • How to describe data with the statistics module
  • How to compare decimal numbers safely
  • What NumPy is and why AI code uses it
  • How to apply a formula to a whole list of numbers at once

Python as your maths assistant

Everything in this course can be calculated in Python. This lesson gathers the tools together, so you can check any calculation, test any formula and explore any function.

The math module

Try it yourselfPython
import math

print("pi:      ", math.pi)
print("e:       ", math.e)
print("sqrt(16):", math.sqrt(16))
print("2 to 10: ", math.pow(2, 10))
print("ln(e):   ", math.log(math.e))
print("log2(32):", math.log2(32))
print("floor:   ", math.floor(3.7), " ceil:", math.ceil(3.2))
print("inf:     ", math.inf > 10 ** 100)

Comparing decimals safely

From the Numbers lesson you know that 0.1 + 0.2 is not exactly 0.3 on a computer. math.isclose() checks whether two numbers are equal within a tiny tolerance:

Try it yourselfPython
import math

a = 0.1 + 0.2
print(a == 0.3)
print(math.isclose(a, 0.3))
print(round(a, 10) == 0.3)

Use math.isclose() whenever you test calculated decimals.

Describing data with statistics

Try it yourselfPython
import statistics

salaries = [30, 32, 35, 36, 38, 40, 250]    # in thousands, one very high value

print("Mean:  ", round(statistics.mean(salaries), 1))
print("Median:", statistics.median(salaries))
print("Spread (standard deviation):", round(statistics.stdev(salaries), 1))

The one very high salary drags the mean up to about 66, while the median, 36, still describes a typical salary. Choosing the right summary is an important skill. You will learn much more in the Statistics course.

A first look at NumPy

So far, every formula has needed a for loop over a list. Real AI data has millions of numbers, and Python loops are too slow for that. NumPy solves this.

Try it yourselfPython
import numpy as np

prices = np.array([100, 250, 80, 40])

print(prices * 2)              # every price doubled, no loop
print(prices + 10)
print(prices.sum(), prices.mean())
print(np.sqrt(np.array([4, 9, 16])))

Compare the loop version and the NumPy version of the mean squared error from the Summation lesson:

Try it yourselfPython
import numpy as np

actual = np.array([3.0, 5.0, 2.5, 7.0])
predicted = np.array([2.5, 5.0, 4.0, 8.0])

mse = np.mean((actual - predicted) ** 2)     # (1/n) Σ (yᵢ - ŷᵢ)²
print("MSE:", mse)

The NumPy line reads almost exactly like the formula. And here is the sigmoid function applied to a whole array of scores at once:

Try it yourselfPython
import numpy as np

scores = np.array([-4.0, -1.0, 0.0, 1.0, 4.0])
probabilities = 1 / (1 + np.exp(-scores))
print(np.round(probabilities, 3))

On your own computer, install NumPy with pip install numpy. In this course's browser examples it is already available, although the first run that uses it takes a few extra seconds to load.

Common mistakes

Practice exercise

Describe a small dataset with Python's built-in maths tools.

Your solutionPython
import math
import statistics

heights_cm = [160, 172, 168, 181, 175, 159]

# 1. Print the mean height, rounded to 1 decimal place.
# 2. Print the median height.
# 3. Print the tallest height minus the shortest (the range).
# 4. Print whether the mean is close to 169 using math.isclose with abs_tol=0.5

# Output must be exactly:
# Mean: 169.2
# Median: 170.0
# Range: 22
# Close to 169: True
Knowledge check

With NumPy, what does np.array([1, 2, 3]) * 2 give?

Summary

  • The math module has square roots, logarithms, π, e, floor and ceiling and more.
  • Compare decimals with math.isclose(), never with ==.
  • The statistics module gives the mean, the median and the spread of a list.
  • NumPy stores numbers in arrays and applies vectorised operations to all of them at once.

You have finished Mathematics Foundations

You can now work with numbers, equations, exponents and logarithms, understand functions and their graphs, from straight lines to sigmoid and ReLU, and read the notation of AI papers: Σ, Greek letters, hats, bars, sets and intervals. You have also turned formulas into Python, which is how maths becomes working AI code.

Where next?

Finished reading? Tick it off to track your progress.