---
title: "Lab: line integrals in code"
heading: Work, circulation and Green's theorem by computer
eyebrow: A9 · Lesson 28 · Lab: line integrals
xp: 60
---

::: hook
Lessons 23 to 27 integrated fields along paths and around loops. In code, a path is a list of points, and a line integral is a sum of $\mathbf F\cdot\Delta\mathbf r$ along it. In this lab you'll write that sum, use it to show that one field's work depends on the path while another's doesn't, check Green's theorem on a circle, compute a polygon's area from its boundary alone, and find the voltage between two points of an electric field by integrating along two different routes.
:::

::: play
- The field is $\mathbf F = (-y^3, x^3)$, which circles the origin more strongly farther out.
- The readout is its circulation around a circle of radius $R$, $\oint\mathbf F\cdot d\mathbf l = \frac{3\pi R^4}{2}$, which Green's theorem gives as $\iint 3(x^2 + y^2)\,dA$.
- Double $R$ and the circulation grows sixteen times: the integrand $3r^2$ grows and so does the area.
:::

```sim plot
view: flow
x: x = -2..2
y: y = -2..2
slider: R = 0.2..1.8 step 0.1 = 1
dx: -y^3
dy: x^3
start: 1, 0 | forward
start: 0.5, 0 | forward
start: 1.5, 0 | forward
grid: 14
readout: circulation around radius R = 3*pi*R^4/2 | digits: 5
```

::: predict
## A field does work 5 J moving a charge from A to B along one path, and 3 J along another. What can you conclude?

- [ ] Nothing: work always depends on the path
- [x] The field is not conservative, and its circulation around the loop formed by the two paths is 2 J
- [ ] The field is conservative
- [ ] One of the measurements must be wrong

::: reveal
It isn't conservative. Going out along the first path and back along the second gives a closed loop with work $5 - 3 = 2$ J, a nonzero circulation. For a conservative field, like an electrostatic one, every loop gives zero and every path gives the same work. A changing magnetic field makes the electric field non-conservative, which is how a transformer works.
:::
:::

::: nameit
## A line integral as a sum

Sample the path at points $\mathbf r_0, \mathbf r_1, \ldots, \mathbf r_n$. Then

$$\int_C\mathbf F\cdot d\mathbf l \approx \sum_k\mathbf F\left(\tfrac{\mathbf r_k + \mathbf r_{k+1}}{2}\right)\cdot(\mathbf r_{k+1} - \mathbf r_k)$$

Evaluating $\mathbf F$ at each segment's midpoint makes the error proportional to the square of the segment length. For a parametrized path, the same sum can be written with $\mathbf r'(t)\,\Delta t$.

## Testing for conservative fields

A field is conservative if its work is the same along every path between two points; equivalently, its circulation around every loop is zero; in a region without holes, equivalently, $\nabla\times\mathbf F = \mathbf 0$. Numerically: compare two different paths, or compute the curl on a grid.

## Green's theorem and areas

$\oint(P\,dx + Q\,dy) = \iint\left(\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y}\right)dA$. With $P = -\frac y2$, $Q = \frac x2$, the right side is the area, so a closed polygon's area comes from its corners alone:

$$A = \frac12\sum_k(x_ky_{k+1} - x_{k+1}y_k)$$

(the **shoelace formula**), positive when the corners run counterclockwise.
:::

::: example
## Find the work of $\mathbf F = (x^2, xy)$ from $(0, 0)$ to $(1, 2)$ along the straight line and along the path that goes right, then up.

::: solution
1. **Straight line.** $\mathbf r = (t, 2t)$ gives
   $$\begin{aligned} W &= \int_0^1 5t^2\,dt \\ &= \tfrac53 \\ &= 1.667 \end{aligned}$$
2. **Right along the $x$ axis.** Here $\mathbf F\cdot d\mathbf l = x^2\,dx$, giving $\frac13$.
3. **Then up the line $x = 1$.** Here $\mathbf F\cdot d\mathbf l = 1 \cdot y\,dy$, giving $\frac{2^2}{2} = 2$.
4. **Total for the bent path.**
   $$\tfrac13 + 2 = 2.333$$
5. **Why they differ.** This field is not conservative. Its curl is
   $$\frac{\partial(xy)}{\partial x} - \frac{\partial(x^2)}{\partial y} = y$$

**Answer:** the straight line gives 1.667 and the right-then-up path gives 2.333.
:::
:::

::: example
## The field $\mathbf E = (2xy, x^2)$ V/m. What is the voltage between $(0, 0)$ and $(2, 1)$ m?

::: solution
1. **Check the curl.**
   $$2x - 2x = 0$$
   so it's conservative.
2. **Find the potential.** $\mathbf E = \nabla(x^2y)$, that is, $V = -x^2y$.
3. **Voltage.**
   $$\begin{aligned} &V(2, 1) - V(0, 0) \\ &= -4\ \text{V} \end{aligned}$$
   The point $(2, 1)$ is 4 V below the origin.
4. **Check along a path.** Along the $x$ axis $\mathbf E\cdot d\mathbf l = 0$; then up $x = 2$,
   $$\int_0^14\,dy = 4\ \text{V}$$
   of work per coulomb, so the potential falls by 4 V.

**Answer:** the point $(2, 1)$ m is 4 V below the origin: $V(2, 1) - V(0, 0) = -4$ V.
:::
:::

::: check
given: R = 0.5 | 1 | 2
answer: 3*pi*R^4/2
tolerance: 0.5%

## What is the circulation of $\mathbf F = (-y^3, x^3)$ counterclockwise around a circle of radius {R}?

::: right
Right. Green's theorem: $\iint 3(x^2 + y^2)\,dA = 3 \cdot 2\pi\frac{R^4}{4}$ = {answer}.
:::

::: misses
- [3*pi*R^4] The polar integral $\int_0^R r^3\,dr$ is $\frac{R^4}{4}$.
- [any] Not yet. Use Green's theorem with $\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} = 3x^2 + 3y^2$.
:::
:::

::: check
given: a = 2 | 3; b = 1 | 4
answer: a*b/2
tolerance: 0.5%

## What does the shoelace formula give for the triangle $(0, 0)$, $(\given{a}, 0)$, $(\given{a}, \given{b})$?

::: right
Right. $\frac12(0 + ab - 0) = \frac{ab}{2}$ = {answer}.
:::

::: misses
- [a*b] That's the rectangle; the triangle is half.
- [any] Not yet. $\frac12\sum(x_ky_{k+1} - x_{k+1}y_k)$ round the three corners.
:::
:::

::: check
kind: python

## Write `line_integral(F, pts)` for a field `F(x, y)` returning a NumPy pair and a path given as an array of points, using midpoints. Set `W` for $\mathbf F = (x^2, xy)$ along 1001 points of the straight line from $(0, 0)$ to $(1, 2)$.

```python starter
import numpy as np

def line_integral(F, pts):
    return 0.0

t = np.linspace(0, 1, 1001)
pts = np.column_stack([t, 2 * t])
W = line_integral(lambda x, y: np.array([x * x, x * y]), pts)
print(W)
```

```python solution
import numpy as np

def line_integral(F, pts):
    total = 0.0
    for a, b in zip(pts[:-1], pts[1:]):
        m = (a + b) / 2
        total += F(m[0], m[1]) @ (b - a)
    return total

t = np.linspace(0, 1, 1001)
pts = np.column_stack([t, 2 * t])
W = line_integral(lambda x, y: np.array([x * x, x * y]), pts)
print(W)
```

```python tests
assert abs(W - 5 / 3) < 1e-5, f"Along the straight line the work is 5/3; got {W}."
```

::: right
Right. With midpoints, a thousand segments are accurate to about a millionth.
:::
:::

::: check
kind: python

## Using your `line_integral` (in the starter), compute the work of $\mathbf F = (x^2, xy)$ from $(0, 0)$ to $(1, 2)$ along "right, then up" (two straight legs of 1001 points each). Set `W2` and `diff = W2 - 5/3`.

```python starter
import numpy as np

def line_integral(F, pts):
    total = 0.0
    for a, b in zip(pts[:-1], pts[1:]):
        m = (a + b) / 2
        total += F(m[0], m[1]) @ (b - a)
    return total

W2 = diff = 0.0
print(W2, diff)
```

```python solution
import numpy as np

def line_integral(F, pts):
    total = 0.0
    for a, b in zip(pts[:-1], pts[1:]):
        m = (a + b) / 2
        total += F(m[0], m[1]) @ (b - a)
    return total

F = lambda x, y: np.array([x * x, x * y])
s = np.linspace(0, 1, 1001)
leg1 = np.column_stack([s, 0 * s])
leg2 = np.column_stack([1 + 0 * s, 2 * s])
W2 = line_integral(F, leg1) + line_integral(F, leg2)
diff = W2 - 5 / 3
print(W2, diff)
```

```python tests
assert abs(W2 - 7 / 3) < 1e-5, f"Right then up gives 1/3 + 2 = 7/3; got {W2}."
assert abs(diff - 2 / 3) < 1e-5, "The two paths differ by 2/3: the field isn't conservative."
```

::: right
Right. A difference of $\frac23$ between paths, which equals the integral of the curl, $y$, over the triangle between them.
:::
:::

::: check
kind: python

## Check Green's theorem for $\mathbf F = (-y^3, x^3)$ on the unit circle: compute the circulation with 20 001 points and set `circ`, and set `area_integral` to $\iint 3(x^2 + y^2)\,dA$ evaluated in closed form.

```python starter
import numpy as np

circ = area_integral = 0.0
print(circ, area_integral)
```

```python solution
import numpy as np

t = np.linspace(0, 2 * np.pi, 20001)
x, y = np.cos(t), np.sin(t)
xm, ym = (x[1:] + x[:-1]) / 2, (y[1:] + y[:-1]) / 2
circ = np.sum(-ym**3 * np.diff(x) + xm**3 * np.diff(y))
area_integral = 3 * np.pi / 2
print(circ, area_integral)
```

```python tests
import math
assert abs(area_integral - 3 * math.pi / 2) < 1e-12, "The area integral is 3 pi / 2."
assert abs(circ - 3 * math.pi / 2) < 1e-4, f"The circulation should match 3 pi / 2 = 4.712; got {circ}."
```

::: right
Right. Boundary and interior agree, as Green's theorem promises.
:::
:::

::: check
kind: python

## Write `shoelace(xs, ys)` returning a polygon's signed area. Set `A` for the pentagon with corners $(0, 0)$, $(4, 0)$, $(5, 3)$, $(2, 5)$, $(-1, 3)$ in order.

```python starter
import numpy as np

def shoelace(xs, ys):
    return 0.0

A = shoelace(np.array([0, 4, 5, 2, -1.0]), np.array([0, 0, 3, 5, 3.0]))
print(A)
```

```python solution
import numpy as np

def shoelace(xs, ys):
    return 0.5 * np.sum(xs * np.roll(ys, -1) - np.roll(xs, -1) * ys)

A = shoelace(np.array([0, 4, 5, 2, -1.0]), np.array([0, 0, 3, 5, 3.0]))
print(A)
```

```python tests
import numpy as np
assert abs(A - 21) < 1e-12, f"The pentagon's area is 21; got {A}."
assert abs(shoelace(np.array([0, 0, 4.0]), np.array([0, 3, 0.0])) + 6) < 1e-12, "Clockwise corners give a negative area: -6 for this triangle."
```

::: right
Right. The area comes from the corners alone: Green's theorem in its simplest form.
:::
:::

::: check
kind: python

## For $\mathbf E = (2xy, x^2)$ V/m, use your `line_integral` (in the starter) to integrate from $(0, 0)$ to $(2, 1)$ along a straight line and along a parabola $y = x^2/4$, and set `V1` and `V2` to the voltage $-\int\mathbf E\cdot d\mathbf l$ along each.

```python starter
import numpy as np

def line_integral(F, pts):
    total = 0.0
    for a, b in zip(pts[:-1], pts[1:]):
        m = (a + b) / 2
        total += F(m[0], m[1]) @ (b - a)
    return total

V1 = V2 = 0.0
print(V1, V2)
```

```python solution
import numpy as np

def line_integral(F, pts):
    total = 0.0
    for a, b in zip(pts[:-1], pts[1:]):
        m = (a + b) / 2
        total += F(m[0], m[1]) @ (b - a)
    return total

E = lambda x, y: np.array([2 * x * y, x * x])
s = np.linspace(0, 1, 2001)
line = np.column_stack([2 * s, s])
para = np.column_stack([2 * s, (2 * s)**2 / 4])
V1 = -line_integral(E, line)
V2 = -line_integral(E, para)
print(V1, V2)
```

```python tests
assert abs(V1 + 4) < 1e-5 and abs(V2 + 4) < 1e-5, f"Both paths give -4 V (V = -x^2 y); got {V1}, {V2}."
```

::: right
Right. A conservative field gives the same voltage along both routes: the potential difference is a property of the endpoints.
:::
:::

::: explain
## Why is the shoelace formula a special case of Green's theorem?

::: model
Green's theorem turns a circulation around a closed boundary into an integral of $\frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y}$ over the inside. Choosing $P = -\frac y2$ and $Q = \frac x2$ makes that integrand 1, so the double integral is the area, and the area equals $\frac12\oint(x\,dy - y\,dx)$. On a polygon the boundary is straight segments, and along each segment the integral works out exactly to $\frac12(x_ky_{k+1} - x_{k+1}y_k)$. Adding them gives the shoelace formula, which is why it needs only the corners and why its sign records the direction you went round.
:::
:::

::: practice

::: check
given: R = 0.1..3
answer: 3*pi*R^4/2
tolerance: 0.5%

## Circulation of $(-y^3, x^3)$ around radius {R}?

::: misses
- [any] $\frac{3\pi R^4}{2}$.
:::
:::

::: check
given: a = 0.5..10; b = 0.5..10
answer: a*b/2
tolerance: 0.5%

## Shoelace area of $(0, 0)$, $(\given{a}, 0)$, $(\given{a}, \given{b})$?

::: misses
- [any] $\frac{ab}{2}$.
:::
:::
:::
