Whole-array Operations
As mentioned in the last tutorial, one of the biggest advantages of using arrays is the greatly improved computational efficiency. This reflects on how we apply the usual arithmetic operations to them in Python. Previously, a naive way to add two lists of numbers component/element-wise may utilize for loops (as well as the zip function, see this tutorial):
x = [1,2,3,4,5]y = [-3,1,1,5,-2]z = []for a, b in zip(x,y): c = a + b z.append(c)print(z)
Although this can give the correct result: [-2, 3, 4, 9, 3], this looks very clumsy and actually has poor computational efficiency (if the size of the lists gets increasingly larger). However, with the help of NumPy, we can do the following:
import numpy as npx = np.array([1,2,3,4,5])y = np.array([-3,1,1,5,-2])z = x + yprint(z)
that produces [-2 3 4 9 3] too. We have directly added two arrays together element-wise in a very clean and readable manner without involving any for loop. This is known as a whole-array operation, or described as vectorized (akin to vector addition/subtraction/product in maths). Such operations are, in fact, extremely computationally efficient, as they internally call some advanced features of the computer’s CPU for acceleration. Of course, this requires that the two arrays are of the same shape.

Let’s use the same two arrays to showcase how the other common arithmetic operations are done in a similarly element-wise fashion:
print(x-y)print(x*y)print(x/y)print(x.astype(float)**y) # Power operations involving negative exponents need x to be of the float type: see the last tutorial.
will produce
[ 4 1 2 -1 7][ -3 2 3 20 -10][-0.33333333 2. 3. 0.8 -2.5 ][1.000e+00 2.000e+00 3.000e+00 1.024e+03 4.000e-02]
We can also add/subtract/multiply/etc. the entire array by a single number using the same syntax:
print(x-1)print(x*2)
will give [0 1 2 3 4] and [ 2 4 6 8 10].
Example
An illustrative example will be the calculation of BMI (recall this tutorial). If we have the heights and weights of a group of people, then we can put them in two arrays and proceed with the usual formula but now applied to all entries at the same time:
heights = np.array([1.7, 1.65, 1.52, 1.88, 1.81])weights = np.array([74, 55, 51, 89, 78])BMI = weights / heights**2print(BMI)
which outputs [25.60553633 20.2020202 22.07409972 25.18107741 23.80879705]. We can also do this with the function as demonstrated in the aforementioned tutorial. The form of the function will be the same, it is just that the quantities involved are now arrays.
heights = np.array([1.7, 1.65, 1.52, 1.88, 1.81])weights = np.array([74, 55, 51, 89, 78])def calculate_BMI(height, weight): BMI = weight / height**2 return(BMI)BMI = weights / heights**2print(BMI)
Mathematical Functions
As a numerical library, NumPy also offers the computation of many commonly used mathematical functions like the exponential (np.exp), logarithm (np.log), and trigonometric functions (np.sin, np.cos, …). They are then applied to each number in an array at once, as in the whole-array operations above. For instance,
x = np.arange(1, 5)print(np.exp(x))print(np.log(x))print(np.sin(x))
produces
[ 2.71828183 7.3890561 20.08553692 54.59815003][0. 0.69314718 1.09861229 1.38629436][ 0.84147098 0.90929743 0.14112001 -0.7568025 ]
Notice that for trigonometric functions, the unit of radians is assumed for the angle. Therefore, to obtain the usual result for degrees, we either need to use the np.pi constant for \( \pi \) (1 deg = \( \pi/180 \) rad), or the np.deg2rad function:
x = np.linspace(0,90,10)print(np.cos(x*np.pi/180)) # or print(np.cos(np.deg2rad(x)))
that gives [1.00000000e+00 9.84807753e-01 9.39692621e-01 8.66025404e-01.
7.66044443e-01 6.42787610e-01 5.00000000e-01 3.42020143e-01
1.73648178e-01 6.12323400e-17]
Exercise
The range of projectile motion is given by the formula
\begin{equation}
R = \frac{v_0^2\sin(2\theta)}{g}
\end{equation}
where \( v_0 \) is the initial speed, \( \theta \) is the shooting angle (relative to the horizontal), and \( g \) is the gravitational acceleration. Write a function that accepts a value of \( v_0 \) and a list of angles \(\theta\), and computes the ranges at these different angles under the same initial speed, let’s say \( v_0 = 5 \) and \( \theta = 0^\circ,30^\circ,45^\circ,60^\circ,90^\circ \).
Suggested Solution
def range(v_0, theta, g=9.81): theta_rad = np.deg2rad(theta) R = v_0**2 * np.sin(2*theta_rad) / g return(R)theta = [0,30,45,60,90]print(range(v_0=5,theta=theta))
This gives [0.00000000e+00 2.20699644e+00 2.54841998e+00 2.20699644e+00. Notice the small numerical error when calculating for \( \theta = 90^\circ \), and that we need to convert the angles from degrees to radians. In doing so, the
3.12091437e-16]np.deg2rad function automatically converts the list to an array as well, so we don’t need to explicitly call np.array.







Leave a Reply