NumPy Exercises#
These exercises combine concepts from NumPy Basics and Array Operations.
Work through each exercise, then check your solution.
Exercise 1: Average Atomic Mass#
The isotopes of tin have the following mass numbers and natural abundances:
Mass number |
Abundance |
---|---|
112 |
0.0097 |
114 |
0.0066 |
115 |
0.0034 |
116 |
0.1454 |
117 |
0.0768 |
118 |
0.2422 |
119 |
0.0859 |
120 |
0.3258 |
122 |
0.0463 |
124 |
0.0579 |
Create two arrays: one for the mass numbers and one for the abundances. Then use vector arithmetic to calculate the average (mean) mass of naturally occurring tin.
Exercise 2: Molecular Distances#
You have an ammonia molecule (NH₃) with the following atomic coordinates (in Ångströms):
atom_N = [0.0, 0.0, 0.0] # Nitrogen at origin
atom_H1 = [0.0, 0.94, 0.38] # Hydrogen 1
atom_H2 = [0.81, -0.47, 0.38] # Hydrogen 2
atom_H3 = [-0.81, -0.47, 0.38] # Hydrogen 3
In the Loops exercises, you used nested loops to calculate all pairwise distances. Now rewrite this calculation using NumPy arrays to store the atom positions and vector arithmetic to calculate the distances.
Tasks:
Store the atom positions as a 2D NumPy array (4 atoms × 3 coordinates)
Use nested loops to iterate over unique pairs of atoms
For each pair, use NumPy vector arithmetic and
np.linalg.norm()
to calculate the distance
Exercise 3: Analysis of Experimental Data#
You’ve measurexd the absorbance of a solution at 540 nm over time to monitor a reaction. Here are your measurements (arbitrary units):
times = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] # minutes
absorbance = [1.85, 1.52, 1.31, 1.08, 0.89, 0.71, 0.58, 0.49, 0.38, 0.32, 0.28]
Tasks:
Convert the data to NumPy arrays
Calculate the mean and standard deviation of the absorbance values
Calculate the change in absorbance between consecutive time points (hint: you can use array slicing like
absorbance[1:] - absorbance[:-1]
)Find the time point where the absorbance first drops below 0.5
Use NumPy functions and array operations where possible.