Functions
Learn about functions, implement them in Python, and visualize them.
What’s a function?
A function is like a machine that takes input and generates output. Most machines have different settings that regulate the output (typically, a button pad is there to modify the settings). These settings are called the parameters of the function.
Example of a function
For example, in , is a function, and are two inputs, and are two parameters, and is the function’s output.
Functions in Python
Remember: This course uses Python. If you’re not fluent in Python, you may find this course very helpful.
Here’s how we can experiment with the function in the example above in Python:
def f(x1,x2):a , b = 2 , -4output = a*x1 + b*x2return outputx1 , x2 = 5 , 7c = f(x1, x2)print(c)
Formal definition
Formally, a function is a relation from a set of inputs to a set of possible outputs, where each input is related to exactly one output.
This means that if an object, , is in the set of inputs (called the domain), then a function, , maps the object, , to precisely one object, , in the set of possible outputs (called the codomain).
Generality of a function’s input and output
The input, , and output, , of a function can be any object, such as an array, matrix, tensor, and so on. A matrix is a two-dimensional array, whereas a tensor is an array of several (typically more than two) dimensions. Don’t worry about this too much. We’ll learn about matrices, vectors, and tensors in detail in subsequent lessons.
Example: Array input, scalar output
The following function adds the elements of the input array and returns the sum.
import numpy as npdef f(x):return np.sum(x)print(f(np.array([-1, 3, 4.6, 0, 9])))
Example: Array input, array output
The following function sorts the input array in ascending order: where
import numpy as npdef f(x):return np.sort(x)print(f(np.array([3, 4, 6, 1, 2, -1, 0, 9])))
Visualization of a function
Visualizing a function can be beneficial. In data analysis, visualization can give a better insight into the relationship between input and output.
Visualizing polynomials
Let’s visualize some simple polynomial functions: and .
import numpy as npimport matplotlib.pyplot as pltx = np.arange(0., 5., 0.2)plt.plot(x, x**2, 'bs', x, x**3, 'g^')plt.xlabel('x');plt.ylabel('f(x)')plt.legend(['x^2', 'x^3'], loc='upper left')
Visualizing planes in 3D
A plane in 3D can be viewed as a function, . If is , then the plane passes through the origin and forms a subspace (more on this later).
Note: We can also interact with the 3D plot using the following app. Launch the app and then press the “Run” button inside the “Jupyter” notebook. Use your mouse to rotate and zoom the plot. Feel free to edit the code and experiment with the parameters and code.