Vectors
A vector is a quantity with both a size and a direction, such as a velocity, a force or the step from one point to another. This lesson covers components, addition, scaling, length and unit vectors, and shows how NumPy arrays make all of it one-liners.
Arrows and components
A scalar is a single number (a temperature, a mass). A vector has a magnitude (length) and a direction. You can draw it as an arrow, but for computing you write it as a list of components:
A vector has no fixed position. The arrow from to and the arrow from to are the same vector . The vector from point to point is , the displacement. A position vector is the special case that starts at the origin.
The basic operations
| Operation | Formula (2D) | Meaning |
|---|---|---|
| Addition | tip-to-tail: walk , then walk | |
| Subtraction | the arrow from 's tip to 's tip | |
| Scalar multiple | stretch by ; a negative flips direction | |
| Magnitude | length (Pythagoras) | |
| Unit vector | same direction, length 1 |
In 3D every formula gets a third component, and the magnitude becomes .
NumPy arrays add and scale component-wise, so the table translates directly:
import numpy as np
a = np.array([3.0, 4.0])
b = np.array([-1.0, 2.0])
print("a + b =", a + b)
print("b - a =", b - a)
print("2.5 * a =", 2.5 * a)
print("|a| =", np.linalg.norm(a))
print("unit a =", a / np.linalg.norm(a))
print("|unit a| =", np.linalg.norm(a / np.linalg.norm(a)))a + b = [2. 6.]
b - a = [-4. -2.]
2.5 * a = [ 7.5 10. ]
|a| = 5.0
unit a = [0.6 0.8]
|unit a| = 1.0
Note: Normalising the zero vector divides by zero. Real code checks the length first, or adds a tiny epsilon, before dividing.
Distance, direction and midpoints
Three questions come up constantly: how far apart are two points, which way does one lie from the other, and where is the point a fraction of the way between them? All three use the displacement :
The last line is linear interpolation (lerp). It is also the vector equation of the line through and : as runs over all real numbers, sweeps out the whole line.
import numpy as np
A = np.array([2.0, -1.0, 3.0])
B = np.array([8.0, 1.0, 6.0])
d = B - A
dist = np.linalg.norm(d)
print("displacement:", d)
print("distance :", dist)
print("direction :", np.round(d / dist, 4))
for t in [0.0, 0.25, 0.5, 1.0]:
print(f"t = {t:4}: {A + t * d}")displacement: [6. 2. 3.]
distance : 7.0
direction : [0.8571 0.2857 0.4286]
t = 0.0: [ 2. -1. 3.]
t = 0.25: [ 3.5 -0.5 3.75]
t = 0.5: [5. 0. 4.5]
t = 1.0: [8. 1. 6.]
The distance is a whole number because .
Vectors in calculus
In calculus, vectors carry rates of change that have a direction. The velocity of a moving point is a vector, its acceleration is a vector, and the gradient of a function of several variables is a vector pointing uphill. The later lessons of this section (motion in space, curves) are about vectors that change with time.
In software
- Games and graphics. Positions, velocities, forces, surface normals and light directions are all 3-vectors. The core game-loop step
position += velocity * dtis vector addition and scaling. See Vectors and Length and Normalize in Game Math. - Machine learning. A data row with 20 features is a 20-dimensional vector, and so is a word embedding with 768 components. The same formulas for length and distance work in any number of dimensions.
- NumPy. Element-wise arithmetic and
np.linalg.norm(see NumPy Linear Algebra) do these operations on millions of vectors at once.
import numpy as np
pos = np.array([0.0, 10.0]) # metres
vel = np.array([4.0, 0.0]) # metres per second
gravity = np.array([0.0, -9.8])
dt = 0.1
for step in range(3):
vel = vel + gravity * dt
pos = pos + vel * dt
print(f"step {step + 1}: pos = {np.round(pos, 3)}, speed = {np.linalg.norm(vel):.3f}")step 1: pos = [0.4 9.902], speed = 4.118
step 2: pos = [0.8 9.706], speed = 4.454
step 3: pos = [1.2 9.412], speed = 4.964
Each frame adds a small vector to the velocity and another to the position. That is the semi-implicit Euler integrator covered in Physics Integration in Game Loops.
Exercises
Exercise 1: Combine two vectors
Let and . Compute and its magnitude.
Answer
with magnitude .
Solution
Exercise 2: Unit vector
Find the unit vector in the direction of .
Answer
.
Solution
, so . Check: , so its length is 1.
Exercise 3: A point one third of the way
Find the point one third of the way from to , and the distance .
Answer
The point is . The distance is .
Solution
import numpy as np
P, Q = np.array([1, 5, -2]), np.array([7, -1, 4])
print(P + (Q - P) / 3, round(float(np.linalg.norm(Q - P)), 3))[3. 3. 0.] 10.392
Exercise 4: Fixed-speed movement (code)
An enemy at chases a player at at 5 units per second. Write a function step(enemy, player, speed, dt) that returns the enemy's new position after one frame, and use it to find where the enemy is after 1 second (one step with ).
Answer
: it moves 5 units along the direction .
Solution
Normalise the displacement to get a direction, then scale it by speed * dt. Clamping to the remaining distance stops the enemy from overshooting.
import numpy as np
def step(enemy, player, speed, dt):
d = player - enemy
dist = np.linalg.norm(d)
if dist < 1e-9:
return enemy
move = min(speed * dt, dist)
return enemy + d / dist * move
print(step(np.array([0.0, 0.0]), np.array([30.0, 40.0]), 5.0, 1.0))[3. 4.]
Test yourself
What is the magnitude of ?
- 5
- 3
- 9
Which expression gives the vector from point to point ?
What does multiplying a vector by −2 do?
- Doubles its length and reverses its direction
- Halves its length
- Rotates it by 90°
- Leaves the direction and halves the length