Search⌘ K
AI Features

Coding Example: Implement the behavior of Boids (NumPy approach)

Explore how to implement the behavior of boids using NumPy by vectorizing position and velocity calculations. Learn to compute local neighborhoods, apply flocking rules such as alignment, cohesion, and separation, and visualize the simulation with matplotlib. This lesson helps you understand efficient array operations and simulation techniques using NumPy.

NumPy Implementation

As you might expect, the NumPy implementation takes a different approach and we’ll gather all our boids into a position array and a velocity array:

n = 500
velocity = np.zeros((n, 2), dtype=np.float32)
position = np.zeros((n, 2), dtype=np.float32)

The first step is to compute the local neighborhood for all boids, and for this, we need to compute all paired distances:

#np.subtract.outer  apply the ufunc op to all pairs (a, b) with a in A and b in B.
dx = np.subtract.outer(position[:, 0], position[:, 0])
dy = np.subtract.outer(position[:, 1], position[:, 1])
distance = np.hypot(dx, dy)

We ...