Vector Fields
A vector field attaches an arrow to every point of a region: a wind velocity at each spot on a map, a force at each point in space, a steering direction at each tile of a game level. This lesson gives the precise definition, shows how to draw and compute fields in Python, introduces gradient (conservative) fields and their potential functions, and builds a small potential-field steering demo of the kind game AI and robots use.
Definition
Let be a set in . A vector field on is a function that assigns to each point in a two-dimensional vector . In components,
where and are ordinary scalar functions, called the component functions. A vector field on a set in is the same idea with three components: . We call continuous (or differentiable, or ) when its component functions are.
A useful mental picture: at a sample of points you draw the arrow with its tail at . The arrows are usually scaled down so they do not overlap; only their relative lengths and directions matter for the picture.
| Field | Formula | What it looks like |
|---|---|---|
| Uniform flow | identical arrows everywhere | |
| Rotation (counter-clockwise) | circles around the origin, speed grows with radius | |
| Source | arrows point straight out from the origin | |
| Inverse-square (gravity toward origin) | arrows point in, length | |
| Shear | horizontal arrows, faster higher up |
The rotation field is perpendicular to the position vector, since , so every arrow is tangent to the circle through its point. Its length is .
import numpy as np
import matplotlib.pyplot as plt
def F(x, y): # a rotation plus a weak outward push
return -y + 0.3 * x, x + 0.3 * y
for p in [(1, 0), (0, 2), (-1, -1)]:
P, Q = F(*p)
print(f"F{p} = ({P:+.1f}, {Q:+.1f})")
x, y = np.meshgrid(np.linspace(-2, 2, 13), np.linspace(-2, 2, 13))
P, Q = F(x, y)
plt.figure(figsize=(5, 5))
plt.quiver(x, y, P, Q, np.hypot(P, Q), cmap="viridis")
plt.gca().set_aspect("equal")
plt.title("F = ⟨−y + 0.3x, x + 0.3y⟩: a spiral source")F(1, 0) = (+0.3, +1.0)
F(0, 2) = (-2.0, +0.6)
F(-1, -1) = (+0.7, -1.3)
The arrows swirl counter-clockwise while drifting outward, so a particle carried by this flow spirals away from the origin.
Gradient fields
If is a differentiable function of two or three variables, its gradient is a vector field:
Two facts from that lesson give the picture: points in the direction in which increases fastest, and it is perpendicular to the level curves (or level surfaces) of . So a gradient field crosses the contour lines of a map at right angles, pointing uphill.
A vector field is called conservative if it is the gradient of some scalar function, . Then is called a potential function for . (Physicists usually write with a potential energy ; the minus sign only flips "uphill" to "downhill".) Not every field is conservative: the next lessons give a test, and show why conservative fields are special for line integrals.
import sympy as sp
x, y, z = sp.symbols('x y z')
f = x**2 * y - sp.exp(z) * y + 3 * z
grad = [sp.diff(f, v) for v in (x, y, z)]
print("grad f =", grad)
print("at (1, 2, 0):", [g.subs({x: 1, y: 2, z: 0}) for g in grad])
# a quick check: is <2xy, x**2 - e^z, -y e^z + 3> really this gradient?
F = [2*x*y, x**2 - sp.exp(z), -y*sp.exp(z) + 3]
print("matches:", all(sp.simplify(a - b) == 0 for a, b in zip(F, grad)))grad f = [2*x*y, x**2 - exp(z), -y*exp(z) + 3]
at (1, 2, 0): [4, 0, 1]
matches: True
SymPy prints x**2 for and exp(z) for . At the gradient says that grows fastest in a direction mostly along and slightly up in .
Flow lines
A flow line (streamline) of is a curve whose velocity is the field: . For the pure rotation the flow lines are circles , since . For a gradient field the flow lines are paths of steepest ascent. Tracing flow lines numerically is just solving an ODE, the same Euler step you have seen for direction fields.
In software
- Potential-field steering. Game AI and mobile robots often steer by a potential , moving a little along every frame. The agent slides downhill to the goal and around obstacles without any path search. The weakness is local minima, places where the forces cancel short of the goal, which is why games combine it with A* paths.
- Flow fields for crowds. Strategy games precompute one vector per grid cell pointing along the shortest path to a target; thousands of units then just read the arrow under their feet.
- Fluids, wind and particles. A fluid solver stores a velocity field on a grid; particles, smoke and foliage are advected by sampling it. See the Curl and Divergence lesson for what makes such a field physical.
- ML. Gradient descent follows the flow lines of , the negative gradient field of the loss.
import numpy as np
goal = np.array([8.0, 0.0])
obstacle, radius = np.array([4.0, 0.3]), 1.0
def grad_U(p):
g = 2 * (p - goal) * 0.05 # attraction: U = 0.05·|p − goal|²
d = p - obstacle
dist = np.linalg.norm(d)
if dist < 3 * radius: # repulsion only near the obstacle
g -= 4.0 * d / dist**4 # U = 2/|d|², ∇U = −4·d/|d|⁴
return g
p = np.array([0.0, 0.0])
for step in range(200):
p = p - 0.5 * grad_U(p) # move downhill along −∇U
if step % 40 == 39:
print(f"step {step + 1:3d}: ({p[0]:.2f}, {p[1]:.2f}) "
f"distance to obstacle {np.linalg.norm(p - obstacle):.2f}")step 40: (5.94, -2.03) distance to obstacle 3.03
step 80: (7.73, -0.26) distance to obstacle 3.78
step 120: (7.97, -0.03) distance to obstacle 3.98
step 160: (8.00, -0.00) distance to obstacle 4.01
step 200: (8.00, -0.00) distance to obstacle 4.01
The agent starts heading straight for the goal, gets pushed below the obstacle (its coordinate goes negative) and then settles on the goal at .
Exercises
Exercise 1: Read the arrows
For , compute at , and . Which way do the arrows circulate, and how long is in terms of ?
Answer
, , ; clockwise; .
Solution
Right → down, top → right, left → up: that is clockwise. , and , so the arrows are tangent to circles about the origin.
Exercise 2: A gradient field
Find the gradient field of and evaluate it at .
Answer
; .
Solution
Exercise 3: Find a potential
Find a function with .
Answer
.
Solution
Check: and .
Exercise 4: Inverse-square field (code)
For the gravity-like field , compute at by hand, then write code that evaluates the field there and prints its length.
Answer
, and .
Solution
At the distance is , and . The direction is , so .
import numpy as np
def F(p):
p = np.asarray(p, dtype=float)
return -p / np.linalg.norm(p)**3
v = F([0, 3, 4])
print([round(float(c), 6) for c in v], round(float(np.linalg.norm(v)), 6))[-0.0, -0.024, -0.032] 0.04
The -0.0 is a negative floating-point zero (), equal to 0.
Test yourself
A vector field on is…
- a function that assigns a vector to each point of the plane
- a single vector in the plane
- a function that assigns a number to each vector
- a curve whose tangent is a vector
is called conservative when…
- is constant
- is perpendicular to the position vector
- for some scalar function
- has no zeros
In potential-field steering an agent moves along each frame. What can stop it short of the goal?
- Nothing, it always arrives
- A local minimum of where the attractive and repulsive forces cancel
- The gradient being too large
- being a polynomial