Math
Understand how arithmetic and linear algebra work in NumPy.
Chapter Goals:
- Learn how to perform math operations in NumPy
- Write code using NumPy math functions
A. Arithmetic
One of the main purposes of NumPy is to perform multi-dimensional arithmetic. Using NumPy arrays, we can apply arithmetic to each element with a single operation.
The code below shows multi-dimensional arithmetic with NumPy.
arr = np.array([[1, 2], [3, 4]])# Add 1 to element valuesprint(repr(arr + 1))# Subtract element values by 1.2print(repr(arr - 1.2))# Double element valuesprint(repr(arr * 2))# Halve element valuesprint(repr(arr / 2))# Integer division (half)print(repr(arr // 2))# Square element valuesprint(repr(arr**2))# Square root element valuesprint(repr(arr**0.5))
Using NumPy arithmetic, we can easily modify large amounts of numeric data with only a few operations. For example, we could convert a dataset of Fahrenheit temperatures to their equivalent Celsius form.
The code below converts Fahrenheit to Celsius in NumPy.
def f2c(temps):return (5/9)*(temps-32)fahrenheits = np.array([32, -4, 14, -40])celsius = f2c(fahrenheits)print('Celsius: {}'.format(repr(celsius)))
It is important to note that performing arithmetic on NumPy arrays does not change the original array, and instead produces a new array that is the result of the arithmetic operation.
B. Non-linear functions
...Get hands-on with 1400+ tech skills courses.