Lesson 5 of 12 · Functions and Graphs
What Is a Function?
Learn what a mathematical function is, how to read f(x) notation, what domain and range mean, and how functions combine, with Python versions of every idea.
- 6 min read
- Beginner
- Reviewed
- What a function is, using the idea of a machine
- How to read f(x) notation
- What the domain and the range of a function are
- How functions can be combined, one after another
- Why an AI model is a function
A machine with one rule
Imagine a machine with a slot on one side and a tray on the other. You put a number in, the machine follows its rule, and one number comes out.
The important word is one: a function never gives two different answers for the same input.
f(x) notation
So f(x) = 2x + 1 is a function named f whose rule is "double the input and add 1". Then:
f(3) = 2 × 3 + 1 = 7
f(0) = 2 × 0 + 1 = 1
f(-2) = 2 × -2 + 1 = -3A Python function is a perfect match for a maths function:
def f(x):
return 2 * x + 1
print(f(3))
print(f(0))
print(f(-2))Functions can have any name. In AI you will see g(x), h(x), σ(x) and L(θ), which all work the same way.
Domain and range
import math
def square(x):
return x ** 2
for x in [-3, -1, 0, 2]:
print(f"square({x}) = {square(x)}") # never negative: the range starts at 0
for x in [4, 0, -4]:
try:
print(f"sqrt({x}) = {math.sqrt(x)}")
except ValueError:
print(f"sqrt({x}) is not allowed: {x} is outside the domain")Functions of several inputs
A function can take more than one input and still give one output:
def area(width, height):
return width * height
def bmi(weight_kg, height_m):
return round(weight_kg / height_m ** 2, 1)
print(area(4, 3))
print(bmi(70, 1.75))Mathematicians write these as f(x, y). AI models are functions of many inputs: a house-price model might be f(size, bedrooms, age, location).
Combining functions
def f(x):
return x + 3
def g(x):
return x * 10
print(g(f(2))) # f first: 2 + 3 = 5, then g: 5 x 10 = 50
print(f(g(2))) # g first: 2 x 10 = 20, then f: 20 + 3 = 23The order matters: g(f(x)) is usually different from f(g(x)).
Common mistakes
Write two functions, combine them both ways round, and look at the outputs of one.
# f(x) = x squared, g(x) = x minus 4 # 1. Write f and g as Python functions. # 2. Print g(f(3)) and f(g(3)). # 3. Print the outputs of f for the inputs -2, -1, 0, 1 and 2, on one line, separated by spaces. # Output must be exactly: # g(f(3)) = 5 # f(g(3)) = 1 # 4 1 0 1 4
If f(x) = 3x - 1, what is f(4)?
Summary
- A function turns each input into exactly one output.
f(x)means "the output of f for input x", just like calling a Python function.- The domain is the allowed inputs. The range is the possible outputs.
- Functions can have several inputs, and can be composed:
g(f(x))applies f first. - AI models, and every layer of a neural network, are functions.
Next: drawing functions as graphs, so you can see their shape.
Finished reading? Tick it off to track your progress.