Elementary Mathematics#

We can use Python to solve all kinds of problems in calculus, linear algebra, differential equations and beyond. Let’s take a look at some foundational concepts in Python that are relavant in all branches of mathematics such as numbers, vectors, matrices and functions.

See also

Check out Mathematical Python > Python for more about numbers, variables and functions.

NumPy#

NumPy is an essential Python package for numerical computations. It includes all the mathematical objects and functions that we need to solve problems in calculus, linear algeabra and differential equations. Import the package with the keyword import and use the alias np.

import numpy as np

Numbers#

We can use Python to perform all the usual arithmetic operations:

Operation

Python Syntax

addition

+

subtraction

-

multiplication

*

division

/

exponentiation

**

Let’s do an example from calculus. Recall the Taylor series of the exponential function is:

\[ e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!} = 1 + x + \frac{x^2}{2} + \frac{x^3}{2 \cdot 3} + \frac{x^4}{2 \cdot 3 \cdot 4} + \frac{x^5}{2 \cdot 3 \cdot 4 \cdot 5} + \cdots \]

Let’s use the first 6 terms of the Taylor series to approximate the value:

\[ e^{-1/2} = \frac{1}{\sqrt{e}} \approx 1 - (1/2) + \frac{(1/2)^2}{2} - \frac{(1/2)^3}{2 \cdot 3} + \frac{(1/2)^4}{2 \cdot 3 \cdot 4} - \frac{(1/2)^5}{2 \cdot 3 \cdot 4 \cdot 5} \]
1 - (1/2) + (1/2)**2/2 - (1/2)**3/(2*3) + (1/2)**4/(2*3*4) - (1/2)**5/(2*3*4*5)
0.6065104166666666

Note that we group operations together using parentheses ( ... ) in the computation above.

Constants \(\pi\) and \(e\)#

The constant \(\pi\) is entered as np.pi:

np.pi
3.141592653589793

The constant \(e\) is entered as np.e:

np.e
2.718281828459045

The exponential function \(e^x\) is entered as np.exp therefore \(e=e^1\) is also np.exp(1):

np.exp(1)
2.718281828459045

We should use the function np.exp(x) when computing values of \(e^x\) instead of the exponentiation operation np.e**x.

Variables#

Just like the familiar variables \(x\) and \(y\) in mathematics, we use variables in programming to easily manipulate values. The assignment operator = assigns a value to a variable in Python. For example, let’s compute the values \(y = 1 + x + x^2\) and \(y' = 1 + 2x\) for \(x = 2\). Use the Python function print to display the values of a variable.

x = 2
print(x)
2
y = 1 + x + x**2
print(y)
7
dy = 1 + 2*x
print(dy)
5