Split View: 공업수학 완전정복 4: 벡터 미적분학 - 그린 정리부터 스토크스 정리까지
공업수학 완전정복 4: 벡터 미적분학 - 그린 정리부터 스토크스 정리까지
공업수학 완전정복 4: 벡터 미적분학
벡터 미적분학(Vector Calculus)은 물리학, 전자기학, 유체역학, 그리고 현대 머신러닝에 이르기까지 공학의 모든 분야에서 핵심적으로 사용되는 수학 도구입니다. 이 글에서는 기울기(gradient), 발산(divergence), 회전(curl)의 개념을 바탕으로 그린 정리, 가우스 발산 정리, 스토크스 정리까지 체계적으로 정리합니다.
1. 벡터 함수와 벡터장
벡터값 함수
벡터값 함수(vector-valued function)는 스칼라 매개변수 를 입력받아 벡터를 출력하는 함수입니다.
예를 들어 나선형 곡선(helix)은 다음과 같이 표현됩니다.
접선벡터와 법선벡터
곡선 에서 접선벡터(tangent vector)는 미분으로 구합니다.
단위 접선벡터는 이며, 주법선벡터(principal normal vector)는 입니다.
벡터장
벡터장(vector field)은 공간의 각 점에 벡터를 대응시키는 함수입니다.
대표적 벡터장 예시:
- 중력장:
- 전기장:
- 유체 속도장:
import numpy as np
import matplotlib.pyplot as plt
# 2D 벡터장 시각화
x = np.linspace(-2, 2, 15)
y = np.linspace(-2, 2, 15)
X, Y = np.meshgrid(x, y)
# 회전 벡터장: F = (-y, x)
U = -Y
V = X
fig, ax = plt.subplots(figsize=(6, 6))
ax.quiver(X, Y, U, V, color='steelblue', alpha=0.8)
ax.set_title('Rotational Vector Field F = (-y, x)')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.tight_layout()
plt.show()
2. 스칼라장과 기울기 (Gradient)
방향 도함수
스칼라장 에서 단위벡터 방향의 방향 도함수는 다음과 같습니다.
기울기 벡터
기울기(gradient)는 스칼라장의 최대 증가 방향과 그 크기를 나타냅니다.
물리적 의미:
- 방향: 가 가장 빠르게 증가하는 방향
- : 그 방향의 변화율(기울기의 크기)
- 등위면(level surface)에 수직
예시: 이면
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
# SymPy로 기울기 계산
x_s, y_s = sp.symbols('x y')
f = x_s**2 + y_s**2 + x_s * y_s
grad_x = sp.diff(f, x_s)
grad_y = sp.diff(f, y_s)
print("grad_x =", grad_x) # 2x + y
print("grad_y =", grad_y) # x + 2y
# NumPy로 시각화
x = np.linspace(-2, 2, 20)
y = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x, y)
f_val = X**2 + Y**2
U = 2 * X # df/dx
V = 2 * Y # df/dy
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
c = axes[0].contourf(X, Y, f_val, 20, cmap='viridis')
axes[0].contour(X, Y, f_val, 10, colors='white', alpha=0.5)
plt.colorbar(c, ax=axes[0])
axes[0].set_title('f(x,y) = x² + y² (Level Curves)')
axes[1].quiver(X, Y, U, V, color='red', alpha=0.7)
axes[1].set_title('Gradient ∇f = (2x, 2y)')
plt.tight_layout()
plt.show()
3. 발산 (Divergence)
발산의 정의
벡터장 의 발산(divergence)은 스칼라값입니다.
물리적 의미
발산은 단위 체적당 유체가 흘러나오는(또는 빨려 들어가는) 양을 나타냅니다.
- : 해당 점이 소스(source) — 유체가 밖으로 나감
- : 해당 점이 싱크(sink) — 유체가 안으로 들어감
- : 비압축성 유동(incompressible flow) — 유체가 보존됨
예시: 이면
비압축성 유동의 대표 예시: 이면
import sympy as sp
x, y, z = sp.symbols('x y z')
# 벡터장 F = (x^2, y^2, z^2)
P = x**2
Q = y**2
R = z**2
divergence = sp.diff(P, x) + sp.diff(Q, y) + sp.diff(R, z)
print("div F =", divergence) # 2x + 2y + 2z
4. 회전 (Curl)
회전의 정의
벡터장 의 회전(curl)은 벡터값입니다.
전개하면
물리적 의미와 보존장
- 회전은 유체 입자의 국소적 회전(rotation) 또는 **소용돌이(vorticity)**를 나타냅니다.
- 이면 비회전(irrotational) 또는 보존장(conservative field)
- 보존장이면 퍼텐셜 함수 가 존재하여
Maxwell 방정식과의 관계
패러데이 법칙:
앙페르-맥스웰 법칙:
import sympy as sp
x, y, z = sp.symbols('x y z')
# 벡터장 F = (y*z, x*z, x*y)
P = y * z
Q = x * z
R = x * y
curl_x = sp.diff(R, y) - sp.diff(Q, z)
curl_y = sp.diff(P, z) - sp.diff(R, x)
curl_z = sp.diff(Q, x) - sp.diff(P, y)
print("curl F =", (curl_x, curl_y, curl_z))
# 결과: (0, 0, 0) => 보존장
5. 선적분 (Line Integrals)
스칼라 함수의 선적분
곡선 를 , 로 매개변수화하면
벡터장의 선적분 (일)
벡터장 가 입자를 곡선 를 따라 이동시킬 때 한 일(work):
경로 독립성
인 보존장에서는 경로에 무관하게
즉, 출발점과 도착점만 알면 일을 계산할 수 있습니다.
import numpy as np
from scipy.integrate import quad
# F = (2x, 2y), 곡선: r(t) = (t, t^2), t in [0,1]
def work_integrand(t):
x_t = t
y_t = t**2
# F(r(t)) = (2x, 2y) = (2t, 2t^2)
Fx = 2 * x_t
Fy = 2 * y_t
# r'(t) = (1, 2t)
dx = 1
dy = 2 * t
return Fx * dx + Fy * dy
work, _ = quad(work_integrand, 0, 1)
print(f"Work = {work:.4f}") # = 2.0 (경로 무관: phi = x^2+y^2, phi(1,1)-phi(0,0) = 2)
6. 면적분 (Surface Integrals)
스칼라 함수의 면적분
매개변수 곡면 에서
플럭스 (Flux)
벡터장 가 곡면 를 통과하는 플럭스(flux):
이는 단위 시간에 곡면을 통과하는 유체의 양(체적 유량)을 나타냅니다.
7. 그린 정리 (Green's Theorem)
정리
단순 닫힌 곡선 와 그로 둘러싸인 영역 에서, 와 가 연속 편도함수를 가지면
(단, 는 의 경계를 반시계 방향으로 순회)
면적 계산 응용
그린 정리를 이용하면 닫힌 곡선의 내부 면적을 선적분으로 구할 수 있습니다.
유체역학 응용
2D 유동에서 순환(circulation)과 플럭스를 정량화하는 데 활용됩니다.
import numpy as np
from scipy.integrate import dblquad
# Green's theorem 검증
# C: 원점 중심 반지름 1인 단위원
# P = -y, Q = x => dQ/dx - dP/dy = 1 + 1 = 2
# 이중적분: 2 * pi * 1^2 = 2*pi
# 선적분: ∮ (-y dx + x dy) = 2 * area = 2*pi
result, _ = dblquad(
lambda y, x: 2.0, # integrand = dQ/dx - dP/dy
-1, 1,
lambda x: -np.sqrt(1 - x**2),
lambda x: np.sqrt(1 - x**2)
)
print(f"Double integral = {result:.5f}") # ≈ 6.28318 = 2*pi
8. 가우스 발산 정리 (Divergence Theorem)
정리
체적 와 그 경계면 에서, 가 연속 편도함수를 가지면
여기서 은 외향 단위 법선벡터입니다.
물리적 의미
체적 내의 총 발산(소스/싱크의 합) = 경계면을 통해 나가는 총 플럭스
전기장 가우스 법칙
이는 발산 정리의 직접적인 응용으로, 전하 분포로부터 전기장을 계산하는 데 사용됩니다.
import sympy as sp
x, y, z = sp.symbols('x y z')
# F = (x^3, y^3, z^3), 구 r=1
P, Q, R = x**3, y**3, z**3
div_F = sp.diff(P, x) + sp.diff(Q, y) + sp.diff(R, z)
print("div F =", div_F) # 3x^2 + 3y^2 + 3z^2
# 구 좌표로 적분: 구 내부 3*(x^2+y^2+z^2) dV = 3 * (4/5)*pi (반지름 1)
# 정답: 12*pi/5
print("Expected flux =", 12 * sp.pi / 5)
9. 스토크스 정리 (Stokes' Theorem)
정리
방향이 정해진 곡면 와 그 경계 곡선 에서
- 좌변: 의 에 대한 선적분 (순환, circulation)
- 우변: 의 컬(curl)의 에 대한 면적분
그린 정리와의 관계
그린 정리는 스토크스 정리의 2차원 특수 경우입니다. 가 -평면의 영역 이고 이면
앙페르 법칙
스토크스 정리를 이용하면 이를 미분 형식인 로 변환할 수 있습니다.
import numpy as np
# Stokes 정리 수치 검증
# F = (-y, x, 0), S: 반지름 R=1인 반구 (z >= 0), C: 단위원
# curl F = (0, 0, dQ/dx - dP/dy) = (0, 0, 2)
# 면적분: 2 * area(S 투영) = 2 * pi
# 선적분: ∮ F·dr = ∮ (-y dx + x dy) = 2 * 면적(원) = 2*pi
R = 1.0
# 선적분 (수치)
t = np.linspace(0, 2 * np.pi, 10000)
x_c = R * np.cos(t)
y_c = R * np.sin(t)
dx = np.gradient(x_c, t)
dy = np.gradient(y_c, t)
F_dot_dr = (-y_c) * dx + x_c * dy
line_integral = np.trapz(F_dot_dr, t)
print(f"Line integral ≈ {line_integral:.5f}") # ≈ 2*pi ≈ 6.28318
print(f"2*pi = {2*np.pi:.5f}")
10. 공학 및 AI 응용
유체역학 (CFD)
계산 유체역학(Computational Fluid Dynamics)에서 나비에-스토크스(Navier-Stokes) 방정식은 발산과 회전을 핵심적으로 사용합니다.
비압축성 조건:
Maxwell 방정식 (전자기학)
| 법칙 | 미분형 | 물리적 의미 |
|---|---|---|
| 가우스 전기 법칙 | 전하가 전기장의 소스 | |
| 가우스 자기 법칙 | 자기 단극자 없음 | |
| 패러데이 법칙 | 변하는 자기장이 전기장 유도 | |
| 앙페르-맥스웰 | 전류와 변하는 전기장이 자기장 유도 |
컴퓨터 그래픽스
3D 렌더링에서 조명 계산을 위한 법선벡터(normal vector)는 면적분의 와 동일한 개념입니다. 퐁(Phong) 셰이딩, 범프 매핑 등에 직접 활용됩니다.
머신러닝의 Gradient Descent
경사 하강법(gradient descent)은 기울기 의 반대 방향으로 파라미터를 업데이트합니다.
이는 벡터 미적분학의 기울기 개념을 고차원 파라미터 공간에 직접 적용한 것입니다.
Physics-Informed Neural Networks (PINNs)
PINNs는 손실 함수에 물리 방정식(편미분방정식)을 포함시켜 벡터 미적분 연산자(gradient, divergence, curl)를 자동 미분으로 계산합니다.
여기서 는 예를 들어 같은 비압축 조건 위반 패널티입니다.
11. Python 종합 구현 예제
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import dblquad, quad
import sympy as sp
print("=== 벡터 미적분학 Python 계산 예제 ===\n")
# --- 1. 기울기 계산 ---
x_s, y_s, z_s = sp.symbols('x y z')
f = x_s**3 + y_s**2 * z_s - x_s * y_s
grad = [sp.diff(f, var) for var in (x_s, y_s, z_s)]
print("1. 기울기 (Gradient)")
print(f" f = {f}")
print(f" ∇f = {grad}\n")
# --- 2. 발산 계산 ---
P = x_s**2 * y_s
Q = y_s**2 * z_s
R = z_s**2 * x_s
divergence = sp.diff(P, x_s) + sp.diff(Q, y_s) + sp.diff(R, z_s)
print("2. 발산 (Divergence)")
print(f" F = ({P}, {Q}, {R})")
print(f" div F = {divergence}\n")
# --- 3. 회전 계산 ---
curl_x = sp.diff(R, y_s) - sp.diff(Q, z_s)
curl_y = sp.diff(P, z_s) - sp.diff(R, x_s)
curl_z = sp.diff(Q, x_s) - sp.diff(P, y_s)
print("3. 회전 (Curl)")
print(f" curl F = ({sp.simplify(curl_x)}, {sp.simplify(curl_y)}, {sp.simplify(curl_z)})\n")
# --- 4. 그린 정리 수치 검증 ---
# P = -y, Q = x, 단위 원판
# 이중적분: ∬ (1 + 1) dA = 2 * pi
result, _ = dblquad(
lambda y, x: 2.0,
-1, 1,
lambda x: -np.sqrt(max(0, 1 - x**2)),
lambda x: np.sqrt(max(0, 1 - x**2))
)
print("4. 그린 정리 검증")
print(f" 이중적분 ≈ {result:.5f}, 2π ≈ {2*np.pi:.5f}\n")
# --- 5. 시각화 ---
x_arr = np.linspace(-2, 2, 20)
y_arr = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x_arr, y_arr)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
# 기울기장
U1 = 2 * X
V1 = 2 * Y
axes[0].quiver(X, Y, U1, V1, color='crimson', alpha=0.7)
axes[0].set_title('Gradient of x²+y²')
# 소용돌이장 (curl != 0)
U2 = -Y
V2 = X
axes[1].quiver(X, Y, U2, V2, color='steelblue', alpha=0.7)
axes[1].set_title('Rotational Field (-y, x)')
# 발산장 (source)
U3 = X
V3 = Y
axes[2].quiver(X, Y, U3, V3, color='forestgreen', alpha=0.7)
axes[2].set_title('Source Field (x, y)')
plt.tight_layout()
plt.savefig('vector_fields.png', dpi=120)
plt.show()
12. 퀴즈
Q1. 스칼라장 f의 기울기 벡터 ∇f는 등위면(level surface)에 대해 어떤 방향을 향합니까?
정답: 등위면에 수직(법선) 방향을 향합니다.
설명: 기울기 벡터 ∇f는 f가 가장 빠르게 증가하는 방향을 가리키며, 이 방향은 등위면 f = c에 항상 수직입니다. 방향 도함수 공식 D_u f = ∇f · u 에서, 등위면 위의 접선 방향 t에 대해서는 D_t f = 0 이므로 ∇f ⊥ t 임을 알 수 있습니다.
Q2. 벡터장 F의 발산이 모든 점에서 0이면 (div F = 0), 이 유동을 무엇이라 합니까?
정답: 비압축성 유동(incompressible flow) 또는 솔레노이달(solenoidal) 벡터장이라 합니다.
설명: div F = ∇·F = 0 은 단위 체적당 유체의 순 유출입이 없음을 의미합니다. 물과 같이 밀도가 거의 일정한 유체의 유동이 이에 해당하며, 이 조건은 연속 방정식(continuity equation)에서 비롯됩니다. 자기장 B 역시 ∇·B = 0 을 만족하여 솔레노이달 벡터장입니다.
Q3. 그린 정리에서 ∮C P dx + Q dy = ∬D (∂Q/∂x - ∂P/∂y) dA를 이용하여 폐곡선 C 내부의 면적을 어떻게 구합니까?
정답: P = -y/2, Q = x/2 로 설정하면 A = (1/2) ∮C (x dy - y dx) 로 면적을 구할 수 있습니다.
설명: P = -y/2, Q = x/2 로 놓으면 ∂Q/∂x - ∂P/∂y = 1/2 + 1/2 = 1 이 됩니다. 따라서 ∬D 1 dA = A 가 되어 면적이 직접 계산됩니다. 이 방법은 측량학(surveying)에서 다각형의 면적을 꼭짓점 좌표만으로 계산하는 신발끈 공식(shoelace formula)의 기초가 됩니다.
Q4. 스토크스 정리 ∮C F·dr = ∬S (∇×F)·n dS 에서 curl F = 0이면 선적분은 얼마입니까?
정답: 0입니다.
설명: curl F = ∇×F = 0 이면 우변의 면적분이 0이 되므로, 임의의 닫힌 경로에 대한 선적분도 0입니다. 이는 F가 보존장(conservative field)임을 의미하며, 퍼텐셜 함수 φ가 존재하여 F = ∇φ 가 됩니다. 따라서 일은 경로에 무관하고 시작점과 끝점에만 의존합니다 (∫C F·dr = φ(B) - φ(A)).
Q5. 가우스 발산 정리가 전자기학에서 어떻게 응용됩니까?
정답: 가우스 전기 법칙 ∯S E·dA = Q/ε₀ 의 유도에 사용됩니다.
설명: 발산 정리 ∯S E·dA = ∭V (∇·E) dV 와 미분형 가우스 법칙 ∇·E = ρ/ε₀ 를 결합하면 ∭V (ρ/ε₀) dV = Q_enc/ε₀ 가 됩니다. 즉, 닫힌 곡면을 통과하는 총 전기 플럭스는 내부 총 전하량을 ε₀으로 나눈 값과 같습니다. 이를 통해 고도의 대칭성을 가진 전하 분포(구, 원통, 평면)의 전기장을 손쉽게 계산할 수 있습니다.
참고 자료
- Kreyszig, E. — Advanced Engineering Mathematics (10th ed.), Wiley. 벡터 미적분학 및 공업수학 표준 교재.
- MIT OCW 18.02 — Multivariable Calculus (Denis Auroux). ocw.mit.edu
- Stewart, J. — Calculus: Early Transcendentals (9th ed.), Cengage. 선적분, 면적분, 벡터 정리 챕터.
- SciPy Documentation —
scipy.integrate모듈로 다중 적분 수치 계산. scipy.org - SymPy Documentation — 기호 미분·적분 라이브러리. sympy.org
- Griffiths, D.J. — Introduction to Electrodynamics (4th ed.), Cambridge. Maxwell 방정식과 벡터 미적분학의 물리 응용.
Engineering Mathematics 4: Vector Calculus - From Green's Theorem to Stokes' Theorem
Engineering Mathematics 4: Vector Calculus
Vector calculus is the mathematical backbone of virtually every engineering discipline — from classical physics and electromagnetism to fluid dynamics and modern machine learning. This guide builds systematically from vector functions and fields through the three great integral theorems: Green's theorem, the Divergence theorem, and Stokes' theorem.
1. Vector Functions and Vector Fields
Vector-Valued Functions
A vector-valued function maps a scalar parameter to a vector in space.
A classic example is the helix:
Tangent and Normal Vectors
The tangent vector of a curve is obtained by differentiation:
The unit tangent vector is , and the principal unit normal is .
Vector Fields
A vector field assigns a vector to every point in space:
Canonical examples:
- Gravitational field:
- Electric field:
- Fluid velocity field:
import numpy as np
import matplotlib.pyplot as plt
# Visualize a 2D rotational vector field
x = np.linspace(-2, 2, 15)
y = np.linspace(-2, 2, 15)
X, Y = np.meshgrid(x, y)
# F = (-y, x): pure rotation
U = -Y
V = X
fig, ax = plt.subplots(figsize=(6, 6))
ax.quiver(X, Y, U, V, color='steelblue', alpha=0.8)
ax.set_title('Rotational Vector Field F = (-y, x)')
ax.set_xlabel('x')
ax.set_ylabel('y')
plt.tight_layout()
plt.show()
2. Scalar Fields and the Gradient
Directional Derivative
For a scalar field , the directional derivative in the direction of unit vector is:
The Gradient Vector
The gradient captures both the direction of steepest ascent and the rate of increase:
Geometric and physical meaning:
- Direction of : the direction of maximum rate of increase of
- Magnitude : the maximum rate of increase
- is always perpendicular to the level surfaces
Example: For , the gradient is .
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
# Symbolic gradient computation
x_s, y_s = sp.symbols('x y')
f = x_s**2 + y_s**2 + x_s * y_s
grad_x = sp.diff(f, x_s)
grad_y = sp.diff(f, y_s)
print("grad_x =", grad_x) # 2x + y
print("grad_y =", grad_y) # x + 2y
# Numerical visualization
x = np.linspace(-2, 2, 20)
y = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x, y)
f_val = X**2 + Y**2
U = 2 * X # df/dx
V = 2 * Y # df/dy
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
c = axes[0].contourf(X, Y, f_val, 20, cmap='viridis')
axes[0].contour(X, Y, f_val, 10, colors='white', alpha=0.5)
plt.colorbar(c, ax=axes[0])
axes[0].set_title('f(x,y) = x² + y² — Level Curves')
axes[1].quiver(X, Y, U, V, color='red', alpha=0.7)
axes[1].set_title('Gradient ∇f = (2x, 2y)')
plt.tight_layout()
plt.show()
3. Divergence
Definition
The divergence of a vector field is a scalar:
Physical Interpretation
Divergence measures the net outward flux per unit volume at a point:
- : the point is a source — fluid flows outward
- : the point is a sink — fluid flows inward
- : incompressible flow — no net creation or destruction of fluid
Example: For :
The rotational field satisfies (incompressible).
import sympy as sp
x, y, z = sp.symbols('x y z')
P = x**2
Q = y**2
R = z**2
divergence = sp.diff(P, x) + sp.diff(Q, y) + sp.diff(R, z)
print("div F =", divergence) # 2*x + 2*y + 2*z
4. Curl
Definition
The curl of is a vector, computed via the symbolic determinant:
Expanding:
Physical Meaning and Conservative Fields
- The curl measures local rotation or vorticity of a fluid element.
- implies the field is irrotational (conservative).
- A conservative field admits a potential function such that .
Curl in Maxwell's Equations
Faraday's law of induction:
Ampere-Maxwell law:
import sympy as sp
x, y, z = sp.symbols('x y z')
# F = (y*z, x*z, x*y) — a conservative field
P = y * z
Q = x * z
R = x * y
curl_x = sp.diff(R, y) - sp.diff(Q, z)
curl_y = sp.diff(P, z) - sp.diff(R, x)
curl_z = sp.diff(Q, x) - sp.diff(P, y)
print("curl F =", (curl_x, curl_y, curl_z))
# Result: (0, 0, 0) => conservative (irrotational)
5. Line Integrals
Scalar Line Integral
For a curve parameterized by , :
Vector Line Integral (Work)
The work done by a force field moving a particle along :
Path Independence
For a conservative field , the line integral depends only on the endpoints:
import numpy as np
from scipy.integrate import quad
# F = (2x, 2y), path: r(t) = (t, t^2), t in [0,1]
def work_integrand(t):
x_t = t
y_t = t**2
Fx = 2 * x_t # 2x
Fy = 2 * y_t # 2y
dx = 1 # dx/dt
dy = 2 * t # dy/dt
return Fx * dx + Fy * dy
work, _ = quad(work_integrand, 0, 1)
print(f"Work = {work:.4f}") # = 2.0; phi = x^2 + y^2, phi(1,1)-phi(0,0) = 2
6. Surface Integrals
Scalar Surface Integral
For a parametric surface :
Flux Integral
The flux of through a surface measures the volume of fluid crossing per unit time:
7. Green's Theorem
Statement
Let be a positively oriented (counterclockwise), piecewise-smooth, simple closed curve bounding a region . If and have continuous first partial derivatives on an open set containing , then:
Area Calculation
Green's theorem yields an elegant formula for the area enclosed by a curve:
This is the basis of the shoelace formula used in computational geometry to find polygon areas from vertex coordinates.
Fluid Mechanics Application
In 2D fluid flow, Green's theorem relates the circulation around a closed path to the net rotation (vorticity) within the enclosed region.
import numpy as np
from scipy.integrate import dblquad
# Green's theorem verification
# P = -y, Q = x => dQ/dx - dP/dy = 1 + 1 = 2
# Double integral over unit disk: 2 * pi * 1^2 = 2*pi
result, _ = dblquad(
lambda y, x: 2.0,
-1, 1,
lambda x: -np.sqrt(max(0.0, 1 - x**2)),
lambda x: np.sqrt(max(0.0, 1 - x**2))
)
print(f"Double integral = {result:.5f}") # ≈ 6.28318 = 2*pi
print(f"2*pi = {2*np.pi:.5f}")
8. Gauss's Divergence Theorem
Statement
Let be a solid region with boundary surface (outward orientation), and let have continuous first partial derivatives throughout . Then:
Physical Interpretation
The total outward flux through the closed surface equals the total amount of source/sink activity inside. This transforms a difficult surface integral into a potentially easier volume integral (or vice versa).
Gauss's Law for Electric Fields
This is a direct application of the divergence theorem combined with . It allows us to compute electric fields for highly symmetric charge distributions (sphere, cylinder, infinite plane).
import sympy as sp
x, y, z = sp.symbols('x y z')
# F = (x^3, y^3, z^3), integrate over unit sphere
P, Q, R = x**3, y**3, z**3
div_F = sp.diff(P, x) + sp.diff(Q, y) + sp.diff(R, z)
print("div F =", div_F) # 3*x**2 + 3*y**2 + 3*z**2
# In spherical coords: integral of 3*r^2 over unit sphere = 3*(4*pi/5)
# Total flux = 12*pi/5
print("Expected total flux =", sp.Rational(12, 1) * sp.pi / 5)
9. Stokes' Theorem
Statement
Let be an oriented piecewise-smooth surface bounded by a simple, closed, piecewise-smooth curve (oriented consistently with ). Then:
- Left side: line integral of around (circulation)
- Right side: flux of through
Green's Theorem as a Special Case
When is a flat region in the -plane with , Stokes' theorem reduces to Green's theorem:
Ampere's Law
Stokes' theorem converts this integral form to the differential form , one of Maxwell's equations.
import numpy as np
# Numerical verification of Stokes' theorem
# F = (-y, x, 0), S: upper hemisphere of unit sphere, C: unit circle
# curl F = (0, 0, 2)
# Surface integral: 2 * projected area of S onto xy-plane = 2 * pi
# Line integral: circulation around unit circle = 2*pi
R = 1.0
t = np.linspace(0, 2 * np.pi, 10000)
x_c = R * np.cos(t)
y_c = R * np.sin(t)
dx = np.gradient(x_c, t)
dy = np.gradient(y_c, t)
F_dot_dr = (-y_c) * dx + x_c * dy
line_integral = np.trapz(F_dot_dr, t)
print(f"Line integral ≈ {line_integral:.5f}")
print(f"2*pi = {2*np.pi:.5f}")
10. Engineering and AI Applications
Computational Fluid Dynamics (CFD)
The incompressible Navier-Stokes equations — the cornerstone of CFD — rely heavily on divergence and curl:
Incompressibility constraint:
Maxwell's Equations
| Law | Differential Form | Physical Meaning |
|---|---|---|
| Gauss's Law (E) | Charges are sources of the electric field | |
| Gauss's Law (B) | No magnetic monopoles exist | |
| Faraday's Law | Changing magnetic flux induces electric field | |
| Ampere-Maxwell | Current and changing electric flux create magnetic field |
Computer Graphics
In 3D rendering, surface normal vectors for lighting calculations (Phong shading, bump mapping) are computed exactly as from surface parameterization — a direct application of vector calculus.
Gradient Descent in Machine Learning
The gradient descent optimizer updates parameters in the direction opposite to the gradient of the loss:
This is gradient vector calculus applied directly to a high-dimensional parameter space. Variants such as Adam and RMSProp adaptively scale the gradient using its history.
Physics-Informed Neural Networks (PINNs)
PINNs embed physical laws (PDEs involving divergence, curl, gradient) directly into the loss function, using automatic differentiation to evaluate differential operators:
where might be enforcing incompressibility.
11. Comprehensive Python Implementation
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import dblquad, quad
import sympy as sp
print("=== Vector Calculus Python Examples ===\n")
# --- 1. Gradient ---
x_s, y_s, z_s = sp.symbols('x y z')
f = x_s**3 + y_s**2 * z_s - x_s * y_s
grad = [sp.diff(f, v) for v in (x_s, y_s, z_s)]
print("1. Gradient")
print(f" f = {f}")
print(f" grad f = {grad}\n")
# --- 2. Divergence ---
P = x_s**2 * y_s
Q = y_s**2 * z_s
R = z_s**2 * x_s
div_F = sp.diff(P, x_s) + sp.diff(Q, y_s) + sp.diff(R, z_s)
print("2. Divergence")
print(f" F = ({P}, {Q}, {R})")
print(f" div F = {div_F}\n")
# --- 3. Curl ---
curl_x = sp.diff(R, y_s) - sp.diff(Q, z_s)
curl_y = sp.diff(P, z_s) - sp.diff(R, x_s)
curl_z = sp.diff(Q, x_s) - sp.diff(P, y_s)
print("3. Curl")
print(f" curl F = ({sp.simplify(curl_x)}, {sp.simplify(curl_y)}, {sp.simplify(curl_z)})\n")
# --- 4. Green's theorem (numerical) ---
result, _ = dblquad(
lambda y, x: 2.0,
-1, 1,
lambda x: -np.sqrt(max(0, 1 - x**2)),
lambda x: np.sqrt(max(0, 1 - x**2))
)
print("4. Green's Theorem verification")
print(f" Double integral ≈ {result:.5f}, 2*pi ≈ {2*np.pi:.5f}\n")
# --- 5. Vector field visualization ---
x_arr = np.linspace(-2, 2, 20)
y_arr = np.linspace(-2, 2, 20)
X, Y = np.meshgrid(x_arr, y_arr)
fig, axes = plt.subplots(1, 3, figsize=(15, 5))
axes[0].quiver(X, Y, 2*X, 2*Y, color='crimson', alpha=0.7)
axes[0].set_title('Gradient of x²+y²')
axes[1].quiver(X, Y, -Y, X, color='steelblue', alpha=0.7)
axes[1].set_title('Rotational Field (-y, x)')
axes[2].quiver(X, Y, X, Y, color='forestgreen', alpha=0.7)
axes[2].set_title('Source Field (x, y)')
plt.tight_layout()
plt.savefig('vector_fields_en.png', dpi=120)
plt.show()
12. Quiz
Q1. What geometric relationship does the gradient vector ∇f have with level surfaces of f?
Answer: The gradient ∇f is always perpendicular (normal) to the level surface f = c at every point.
Explanation: The gradient points in the direction of steepest ascent of f. For any tangent vector t lying in the level surface, the directional derivative D_t f = ∇f · t = 0 (since f is constant along the surface), proving that ∇f is orthogonal to all tangent directions — hence normal to the surface. This is exploited in computer graphics to compute surface normals and in optimization to identify descent directions.
Q2. A vector field F satisfies div F = 0 everywhere. What does this imply physically and what is F called?
Answer: F is called an incompressible (or solenoidal) vector field. Physically it means no fluid is created or destroyed — sources and sinks are absent.
Explanation: The condition ∇·F = 0 means the net outflow per unit volume at every point is zero, so volume is conserved by the flow. Liquids (at low pressure) and magnetic fields (∇·B = 0, Gauss's law for magnetism, encoding the absence of magnetic monopoles) are canonical examples. For flow simulation, maintaining this constraint is a central challenge in CFD pressure-velocity coupling schemes such as SIMPLE.
Q3. How does Green's theorem allow computation of a region's area from a boundary integral?
Answer: Choose P = -y/2 and Q = x/2, so that ∂Q/∂x - ∂P/∂y = 1. Then ∮C P dx + Q dy = ∬D 1 dA = Area(D), giving A = (1/2) ∮C (x dy - y dx).
Explanation: The key insight is choosing P and Q so the integrand of the double integral equals 1. This transforms the area problem into a boundary traversal, requiring only the curve coordinates — not integration over the interior. Computational applications include the shoelace formula for polygon areas (the discrete version) and planimeter instruments for measuring map areas mechanically.
Q4. Stokes' theorem states ∮C F·dr = ∬S (∇×F)·n dS. If curl F = 0, what must the line integral equal?
Answer: The line integral is 0 for any closed path C bounding a surface over which curl F = 0.
Explanation: With ∇×F = 0 the right-hand side is ∬S 0·n dS = 0. This is equivalent to F being a conservative (irrotational) field, guaranteeing path independence: ∫C F·dr depends only on endpoints, not the path. The potential function φ satisfying F = ∇φ is then found by integrating the components. In electrostatics, E = -∇V (V is voltage) follows from ∇×E = 0 in static fields.
Q5. Explain how the Divergence Theorem connects to Gauss's Law in electrostatics.
Answer: Combining the integral form of Gauss's law ∯S E·dA = Q_enc/ε₀ with the Divergence Theorem ∯S E·dA = ∭V (∇·E) dV yields the differential form ∇·E = ρ/ε₀.
Explanation: The Divergence Theorem converts a surface flux integral to a volume integral over the enclosed charge density ρ. For a sphere of radius r enclosing total charge Q, choosing S as the sphere and using the spherical symmetry of E makes the surface integral trivial: 4πr²E = Q/ε₀, giving E = Q/(4πε₀r²) — Coulomb's law. The theorem thus bridges the local differential law (∇·E = ρ/ε₀) and the global integral law (Gauss's law), and underpins finite-element and finite-volume methods in computational electromagnetics.
References
- Kreyszig, E. — Advanced Engineering Mathematics (10th ed.), Wiley. The standard reference for engineering mathematics.
- MIT OCW 18.02 — Multivariable Calculus (Denis Auroux). ocw.mit.edu
- Stewart, J. — Calculus: Early Transcendentals (9th ed.), Cengage. Chapters on line integrals, surface integrals, and vector theorems.
- Griffiths, D.J. — Introduction to Electrodynamics (4th ed.), Cambridge University Press. Physical applications of all three vector theorems.
- SciPy Documentation —
scipy.integratefor numerical multi-dimensional integration. scipy.org - SymPy Documentation — Symbolic differentiation and integration library. sympy.org
- Raissi, M. et al. — "Physics-informed neural networks," Journal of Computational Physics, 2019. PINNs and vector calculus in deep learning.