Back
In print settings: Save as PDF, turn headers and footers off, turn background graphics on.

Calculus & Analysis

The study of continuous change, from limits to multivariable calculus.

Official Documentation

July 2026

Contents

Overview

  • Calculus of Variations
  • Complex Analysis
  • Derivatives: Rates of Change
  • Differential Equations
  • Differential Forms and Integration
  • Fourier Analysis
  • Functional Analysis
  • The Fundamental Theorem of Calculus
  • Integration: The Art of Accumulation
  • Laplace Transforms
  • Limits and Continuity
  • Mean Value Theorem: The Guarantee of Speed
  • Multiple Integration
  • Multivariable Calculus
  • Mathematical Optimization
  • Partial Differential Equations
  • Sequences and Series
  • The Fundamental Theorems of Vector Calculus
  • Systems of ODEs
  • Taylor and Power Series
  • Vector Fields

Overview

Section Detail

Calculus of Variations

Calculus of Variations

In standard calculus, we find a number xx that minimizes a function f(x)f(x). In the Calculus of Variations, we find a function y(x)y(x) that minimizes an integral J[y]J[y], called a Functional.

J[y]=x1x2L(x,y,y)dxJ[y] = \int_{x_1}^{x_2} L(x, y, y') dx

This is the math behind “nature is lazy”: physics always chooses the path that minimizes “Action.”

The Euler-Lagrange Equation

To find the function y(x)y(x) that makes J[y]J[y] stationary (a minimum or maximum), we solve the Euler-Lagrange Equation:

Lyddx(Ly)=0\frac{\partial L}{\partial y} - \frac{d}{dx} \left( \frac{\partial L}{\partial y'} \right) = 0

Famous Problems

1. The Geodesic

What is the shortest path between two points? In flat space, the Euler-Lagrange equation tells us it is a straight line. On a curved surface (like Earth), it is a Great Circle.

2. The Brachistochrone

What shape of a wire allows a bead to slide from AA to BB in the shortest amount of time under gravity? Hint: It is not a straight line. It is a Cycloid (the path traced by a point on a rolling wheel).

3. Fermat’s Principle

Light travels between two points along the path that takes the least time. This principle alone allows us to derive Snell’s Law of refraction and the law of reflection.

python
1import numpy as np
2 
3# Let's compare the time taken for a bead to slide down a straight line
4# vs. a simple parabola (approximation of a cycloid)
5g = 9.81
6h = 10.0 # Height
7L = 10.0 # Horizontal distance
8 
9# Straight line path
10time_line = np.sqrt(2 * (L**2 + h**2) / (g * h))
11 
12# A curved path (e.g. y = x^2/10) actually allows the bead to pick up
13# speed faster at the start, potentially reducing total time.
14print(f"Time for straight line: {time_line:.2f}s")
15print("Curved paths allow the object to trade potential energy for kinetic energy")
16print("earlier in the run, resulting in a faster average velocity.")
17 

Use Cases

  1. Classical Mechanics: Formulating the “Lagrangian” to find equations of motion.
  2. Structural Engineering: Finding the shape of a bridge that minimizes stress.
  3. Machine Learning: Variational Inference and optimizing neural network weights over a continuous space.

Exercises

In the Calculus of Variations, what is a 'Functional'?

The Euler-Lagrange equation is to functionals what _____ is to regular functions.

Why does light bend when it enters water (Refraction)?

Section Detail

Complex Analysis

Complex Analysis

Complex Analysis is the study of functions of a complex variable z=x+iyz = x + iy. It reveals a profound rigidity: if a complex function is differentiable once, it is differentiable infinitely many times.

Holomorphic Functions

A function f(z)=u(x,y)+iv(x,y)f(z) = u(x, y) + i v(x, y) is holomorphic if it is complex-differentiable. This requires the Cauchy-Riemann Equations: ux=vy,uy=vx\frac{\partial u}{\partial x} = \frac{\partial v}{\partial y}, \quad \frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}

python
1def check_cauchy_riemann(f, z, h=1e-7):
2 # Numerical gradient check
3 dz_x = f(z + h) - f(z)
4 dz_y = f(z + h*1j) - f(z)
5
6 df_dx = dz_x / h
7 df_dy = dz_y / (h*1j)
8
9 # In a holomorphic function, df/dz should be the same
10 # regardless of the direction of the limit.
11 is_holomorphic = abs(df_dx - df_dy) < 1e-5
12 return is_holomorphic, df_dx, df_dy
13 
14# Test f(z) = z^2 (Holomorphic)
15f1 = lambda z: z**2
16print(f"z^2 at 1+i: {check_cauchy_riemann(f1, 1+1j)}")
17 
18# Test f(z) = conj(z) (Non-holomorphic)
19f2 = lambda z: z.conjugate()
20print(f"conj(z) at 1+i: {check_cauchy_riemann(f2, 1+1j)}")

Complex Integration and Cauchy’s Theorem

If ff is holomorphic in a simply connected domain, the line integral along any closed path γ\gamma is zero: γf(z)dz=0\oint_\gamma f(z) dz = 0

However, if the domain has “holes” (singularities), we apply the Residue Theorem: γf(z)dz=2πiRes(f,zk)\oint_\gamma f(z) dz = 2\pi i \sum \text{Res}(f, z_k)

What is the integral of 1/z around a unit circle centered at the origin?

Conformal Mappings

Holomorphic functions are conformal maps, meaning they preserve angles between curves. This property is vital in fluid dynamics and electromagnetism.

python
1import numpy as np
2 
3def transform_grid(f, points):
4 return [f(p) for p in points]
5 
6# Grid of points
7grid = [x + y*1j for x in np.linspace(-1, 1, 5) for y in np.linspace(-1, 1, 5)]
8 
9# Exponential map: mapping lines to circles/rays
10f_exp = lambda z: np.exp(z)
11transformed = transform_grid(f_exp, grid)
12 
13print(f"First 5 Original: {grid[:5]}")
14print(f"First 5 Transformed: {[f'{t:.2f}' for t in transformed[:5]]}")

Laurent Series and Singularities

Functions can be expanded into Laurent series near singularities: f(z)=n=an(zz0)nf(z) = \sum_{n=-\infty}^{\infty} a_n (z-z_0)^n

  • Removable singularity: No negative power terms.
  • Pole of order m: Finite negative terms up to n=mn = -m.
  • Essential singularity: Infinitely many negative power terms.

The function f(z) = exp(1/z) has what type of singularity at z = 0?

Section Detail

Derivatives: Rates of Change

Derivatives: Rates of Change

The derivative is the mathematical tool for measuring change. If limits are about “approaching,” derivatives are about “moving.”

1. The Instantaneous Rate of Change

We define the derivative f(x)f'(x) as the limit of the average rate of change as the interval goes to zero: f(x)=limh0f(x+h)f(x)hf'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h}

Instead of jumping to rules, let’s calculate the slope of f(x)=x2f(x) = x^2 at x=1x=1 by making hh smaller and smaller. This is exactly what your computer does when it performs Numerical Differentiation.

python
1def f(x): return x**2
2 
3x_target = 1.0
4h_values = [0.1, 0.01, 0.001, 0.0001]
5 
6print(f"{'h':<10} | {'Estimated Slope':<15}")
7print("-" * 30)
8 
9for h in h_values:
10 slope = (f(x_target + h) - f(x_target)) / h
11 print(f"{h:<10} | {slope:<15.6f}")
12 
13print("-" * 30)
14print("The limit seems to be 2.0, which matches the power rule (2x).")

2. Linear Approximation

Around a point aa, we can approximate a complex function f(x)f(x) with a simple line defined by the derivative: f(x)f(a)+f(a)(xa)f(x) \approx f(a) + f'(a)(x-a)

This is why derivatives are so powerful: they turn complex, curvy problems into simple, linear ones.

python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4def f(x): return np.sin(x)
5def df(x): return np.cos(x) # Derivative of sin is cos
6 
7a = 1.0 # Point of approximation
8x_range = np.linspace(0, 2, 100)
9 
10# Linear approx: L(x) = f(a) + f'(a)(x-a)
11linear_approx = f(a) + df(a) * (x_range - a)
12 
13plt.plot(x_range, f(x_range), label='True sin(x)', linewidth=2)
14plt.plot(x_range, linear_approx, '--', label='Linear Approx', color='r')
15plt.scatter([a], [f(a)], color='black', zorder=5)
16plt.title("Linear Approximation (Tangent Line) at x=1")
17plt.legend()
18plt.show()

3. The Rules of Calculus

To avoid numerical limits, we use rules. The Chain Rule is particularly vital for modern AI, as it powers backpropagation. ddxf(g(x))=f(g(x))g(x)\frac{d}{dx} f(g(x)) = f'(g(x)) \cdot g'(x)

What is the derivative of f(x) = sin(x^2)?

4. Optimization: Finding Extremes

If a smooth function reaches a peak or valley, its slope must be zero. These are Critical Points.

python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4# f(x) = x^4 - 4x^2
5def f(x): return x**4 - 4*x**2
6def df(x): return 4*x**3 - 8*x # 4x(x^2 - 2) = 0 => x=0, x=±sqrt(2)
7 
8x = np.linspace(-2.5, 2.5, 500)
9plt.plot(x, f(x))
10plt.axhline(0, color='k', alpha=0.3)
11plt.title("Find the valleys: f'(x) = 0")
12plt.show()

5. Summary Check

If f'(x) > 0 on an interval, the function is:

Section Detail

Differential Equations

Differential Equations

In basic calculus, we learn how to find the derivative of a function. In the real world, we often encounter the reverse problem: we know how a system changes, and we want to find the function that describes the system’s state. These are Differential Equations (DEs).

A DE is an equation that relates a function yy to its derivatives. For example: dydx=ky\frac{dy}{dx} = ky This says that the rate of change of yy is proportional to its current value. This is the model for population growth, radioactive decay, and continuously compounded interest.

Separation of Variables

The simplest way to solve a first-order DE is to “separate” the variables so that all yy‘s are on one side and all xx‘s are on the other. Example: Solve dydx=xy\frac{dy}{dx} = xy.

  1. 1ydy=xdx\frac{1}{y} dy = x dx
  2. 1ydy=xdx\int \frac{1}{y} dy = \int x dx
  3. lny=12x2+C\ln|y| = \frac{1}{2}x^2 + C
  4. y=Aex2/2y = Ae^{x^2/2} (where A=eCA = e^C)

Modeling: Newton’s Law of Cooling

Newton’s Law of Cooling states that the rate of change of the temperature TT of an object is proportional to the difference between its temperature and the ambient temperature TaT_a: dTdt=k(TTa)\frac{dT}{dt} = -k(T - T_a)

This equation tells us that a hot cup of coffee cools down quickly at first (when the difference is large) and then slows down as it approaches room temperature.

python
1import numpy as np
2import matplotlib.pyplot as plt
3from scipy.integrate import odeint
4 
5# Define the model: dT/dt = -k(T - Ta)
6def model(T, t, k, Ta):
7 dTdt = -k * (T - Ta)
8 return dTdt
9 
10# Initial conditions
11T0 = 90 # Coffee temperature at t=0
12Ta = 20 # Room temperature
13k = 0.1 # Cooling constant
14t = np.linspace(0, 60, 100) # 60 minutes
15 
16# Solve ODE
17T = odeint(model, T0, t, args=(k, Ta))
18 
19plt.plot(t, T)
20plt.axhline(Ta, color='r', linestyle='--', label='Room Temp')
21plt.xlabel('Time (min)')
22plt.ylabel('Temperature (C)')
23plt.title('Newton\'s Law of Cooling&#039;)
24plt.legend()
25plt.grid(True)
26plt.show()
27 
28print(f"Temperature at 10 mins: {T[16][0]:.2f} C")
29print(f"Temperature at 60 mins: {T[-1][0]:.2f} C")
30 

Linear Systems and Matrices

When we have multiple interdependent variables (like a predator and its prey, or a set of connected water tanks), we use Systems of Differential Equations. x(t)=Ax(t)\mathbf{x}'(t) = A\mathbf{x}(t) The solution to this system is deeply connected to the Eigenvalues and Eigenvectors of the matrix AA. In fact, the general solution is based on the matrix exponential eAte^{At}.

Exercises

What is the general solution to the DE dy/dx = 3y?

In Newton's Law of Cooling, what happens as time approaches infinity?

Which linear algebra concept is most important for solving systems of DEs?

Section Detail

Differential Forms and Integration

Differential Forms and Integration

Differential forms provide a unified framework for the study of integration, Stokes’ theorem, and the geometry of manifolds.

Exterior Algebra and Wedge Products

At each point of a manifold, a differential kk-form is a purely antisymmetric (0,k)(0, k)-tensor. The wedge product \wedge allows us to combine forms: ωη=(1)pqηω\omega \wedge \eta = (-1)^{p q} \eta \wedge \omega where ω\omega is a pp-form and η\eta is a qq-form.

python
1import numpy as np
2 
3def wedge_product_2d(v1, v2):
4 """Calculates the 2-form (area) spanned by two vectors in R3."""
5 # This is effectively the cross product for 1-forms in R3
6 return np.cross(v1, v2)
7 
8a = np.array([1, 0, 0])
9b = np.array([0, 1, 0])
10 
11area_element = wedge_product_2d(a, b)
12print(f"Area element (wedge product): {area_element}")
13print(f"Magnitude (Area): {np.linalg.norm(area_element)}")

The Exterior Derivative

The exterior derivative dd is a operator that transforms a kk-form into a (k+1)(k+1)-form. It generalizes the concepts of gradient, curl, and divergence from vector calculus.

  • If ff is a 0-form (function), dfdf is its gradient.
  • d(dω)=0d(d\omega) = 0 for any form ω\omega.

What is the result of d(d f) for any function f?

Generalized Stokes’ Theorem

The fundamental theorem of calculus, Green’s theorem, and the divergence theorem are all special cases of the generalized Stokes’ theorem: Ωdω=Ωω\int_{\Omega} d\omega = \int_{\partial \Omega} \omega where Ω\partial \Omega is the boundary of Ω\Omega.

In the context of the divergence theorem, what does 'd omega' represent?

Cohomology

The study of closed forms (dω=0d\omega = 0) that are not exact (ωdη\omega \neq d\eta) leads to De Rham Cohomology, which reveals topological information about the underlying space (e.g., the presence of holes).

Section Detail

Fourier Analysis

Fourier Analysis

Fourier Analysis allows us to decompose complex, periodic signals into a sum of simple sine and cosine waves.

Fourier Series

Any periodic function f(x)f(x) with period 2L2L can be represented as: f(x)=a02+n=1(ancosnπxL+bnsinnπxL)f(x) = \frac{a_0}{2} + \sum_{n=1}^{\infty} \left( a_n \cos\frac{n\pi x}{L} + b_n \sin\frac{n\pi x}{L} \right)

python
1import numpy as np
2 
3def square_wave_fourier(x, terms):
4 res = 0
5 for n in range(1, terms + 1, 2):
6 # f(x) = (4/pi) * summation sin(n*x)/n
7 res += (4 / np.pi) * (np.sin(n * x) / n)
8 return res
9 
10x_val = np.pi/2
11print(f"Square wave approx (5 terms) at pi/2: {square_wave_fourier(x_val, 5)}")
12print(f"Square wave approx (100 terms) at pi/2: {square_wave_fourier(x_val, 100)}")

The Fourier Transform

For non-periodic functions, the Fourier Transform f^(ξ)\hat{f}(\xi) maps a function from the time (or space) domain to the frequency domain: f^(ξ)=f(x)e2πixξdx\hat{f}(\xi) = \int_{-\infty}^{\infty} f(x) e^{-2\pi i x \xi} dx

python
1import numpy as np
2 
3# Fast Fourier Transform (FFT)
4signal = np.array([1, 0, 1, 0, 1, 0, 1, 0])
5fft_res = np.fft.fft(signal)
6 
7print(f"Signal: {signal}")
8print(f"FFT Magnitudes: {np.abs(fft_res).round(2)}")
9print("The spike at index 4 represents the fundamental frequency of the oscillation.")

Parseval’s Theorem

Parseval’s Theorem states that the total energy of a signal in the time domain is equal to the total energy in the frequency domain: f(x)2dx=f^(ξ)2dξ\int |f(x)|^2 dx = \int |\hat{f}(\xi)|^2 d\xi

What happens to the Fourier coefficients as the function becomes smoother?

The Fourier Transform of a Gaussian is what type of function?

Section Detail

Functional Analysis

Functional Analysis

Functional analysis studies vector spaces endowed with a limit-related structure (like a metric or topology) and the linear operators acting upon them.

1. Normed Linear Spaces

A Normed Linear Space (V,)(V, \|\cdot\|) is a vector space VV over a field (usually C\mathbb{C} or R\mathbb{R}) with a norm function :V[0,)\|\cdot\|: V \to [0, \infty) satisfying:

  1. Definiteness: v=0    v=0\|v\| = 0 \iff v = 0.
  2. Homogeneity: αv=αv\|\alpha v\| = |\alpha| \cdot \|v\|.
  3. Triangle Inequality: u+vu+v\|u + v\| \le \|u\| + \|v\|.

A Banach Space is a normed linear space that is complete (every Cauchy sequence converges).

2. Hilbert Spaces and Inner Products

A Hilbert Space is a complete inner product space. The inner product ,\langle \cdot, \cdot \rangle satisfies:

  1. Linearity: αu+βv,w=αu,w+βv,w\langle \alpha u + \beta v, w \rangle = \alpha \langle u, w \rangle + \beta \langle v, w \rangle.
  2. Conjugate Symmetry: u,v=v,u\langle u, v \rangle = \overline{\langle v, u \rangle}.
  3. Positive Definiteness: v,v0\langle v, v \rangle \ge 0, with equality only if v=0v=0.

The L2L^2 Space is a primary example, where functions are square-integrable: f,g=abf(x)g(x)dx,f2=abf(x)2dx\langle f, g \rangle = \int_a^b f(x) \overline{g(x)} \, dx, \quad \|f\|_2 = \sqrt{\int_a^b |f(x)|^2 \, dx}

python
1import numpy as np
2 
3# Numerical verification of the Triangle Inequality
4# ||f + g|| <= ||f|| + ||g||
5x = np.linspace(0, 1, 500)
6f = x**2
7g = np.exp(x)
8 
9def norm_l2(y, dx):
10 return np.sqrt(np.trapz(y**2, dx))
11 
12dx = x[1] - x[0]
13n_f = norm_l2(f, x)
14n_g = norm_l2(g, x)
15n_sum = norm_l2(f + g, x)
16 
17print(f"||f||: {n_f:.4f}")
18print(f"||g||: {n_g:.4f}")
19print(f"||f+g||: {n_sum:.4f}")
20print(f"Is {n_sum:.4f} <= {n_f + n_g:.4f}? {n_sum <= n_f + n_g + 1e-9}")

3. Linear Operators

  1. Partial Differential Equations: Proving that a solution exists even if we can’t find it.
  2. Signal Processing: Decomposing complex signals into simple frequencies.
  3. Quantum Mechanics: The state of a particle is a vector in an infinite-dimensional Hilbert space.

Exercises

In functional analysis, what corresponds to the 'Dot Product' of two vectors?

Why do we say that functional analysis deals with 'Infinite Dimensions'?

In the context of the derivative operator, what is f(x) = e^x?

Section Detail

The Fundamental Theorem of Calculus

The Fundamental Theorem of Calculus

The Fundamental Theorem of Calculus (FTC) is the crown jewel of mathematics. It connects two seemingly unrelated concepts: the derivative (slopes) and the integral (areas). Before this discovery, calculating areas was a tedious process of infinite sums. After the FTC, it became a simple matter of finding an anti-derivative.

Part 1: The Area Function

The first part of the theorem states that if we define an “area function” F(x)F(x) that accumulates the area under a function f(t)f(t) from a fixed point aa to xx: F(x)=axf(t)dtF(x) = \int_a^x f(t) \, dt Then the derivative of this area function is simply the original function: F(x)=f(x)F'(x) = f(x)

The Intuition: The rate at which area is being added at point xx is exactly equal to the “height” of the function at that point. If the function is tall, the area grows quickly. If it is zero, the area stops growing.

Part 2: The Shortcut to Integration

The second part provides the formula we use in practice to evaluate definite integrals. If FF is any anti-derivative of ff (meaning F=fF' = f), then: abf(x)dx=F(b)F(a)\int_a^b f(x) \, dx = F(b) - F(a)

This is revolutionary. To find the area under a curve, you don’t need to draw rectangles. You just need to find the “inverse” of the derivative and plug in the endpoints.

python
1import sympy as sp
2 
3# Define the variable and the function
4x = sp.Symbol('x')
5f = x**2
6 
7# Find the anti-derivative (Indefinite Integral)
8F = sp.integrate(f, x)
9print(f"Function: f(x) = {f}")
10print(f"Anti-derivative: F(x) = {F}")
11 
12# Evaluate the definite integral from 0 to 3 using FTC Part 2
13# Integral = F(3) - F(0)
14a, b = 0, 3
15result = F.subs(x, b) - F.subs(x, a)
16 
17print(f"\nIntegral from {a} to {b} of x^2 dx:")
18print(f"F({b}) - F({a}) = {F.subs(x, b)} - {F.subs(x, a)} = {result}")
19 
20# Verify with sympy's definite integral tool
21assert result == sp.integrate(f, (x, a, b))
22 

Why “Fundamental”?

The FTC is fundamental because it shows that differentiation and integration are inverse operations. It turns a geometry problem (area) into an algebra problem (anti-derivatives). Every time a physicist calculates the energy lost by a falling object or an engineer calculates the total stress on a bridge, they are relying on this 300-year-old bridge between two worlds.

Exercises

If F(x) is the integral of f(t) from 0 to x, and f(x) = cos(x), what is F'(x)?

What is the result of applying the FTC to calculate ∫(2x) dx from 1 to 4?

What must be true about the function f(x) for the FTC to apply on the interval [a, b]?

Section Detail

Integration: The Art of Accumulation

Integration: The Art of Accumulation

While derivatives break a function down into its local rates of change, integration builds it back up. Integration is the process of adding up infinitely many tiny pieces to find a whole.

1. The Definite Integral as a Sum

We define the definite integral abf(x)dx\int_a^b f(x) \, dx as the signed area under the curve f(x)f(x) from aa to bb. Formally, this is reached through a Riemann Sum: we divide the area into nn rectangles and take the limit as nn \to \infty.

Instead of just looking at the formula, let’s watch the approximation get better as we add more rectangles.

python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4def f(x): return x * np.sin(x) + 2
5 
6a, b = 0, 10
7n = 10 # Change this to 5, 20, or 100 to see convergence
8 
9x = np.linspace(a, b, 1000)
10x_rect = np.linspace(a, b, n, endpoint=False)
11width = (b - a) / n
12 
13plt.plot(x, f(x), 'k', linewidth=2)
14plt.bar(x_rect, f(x_rect), width=width, align='edge', alpha=0.3, color='blue', edgecolor='b')
15plt.title(f"Riemann Sum Approximation (n={n})")
16plt.show()

2. Numerical Integration: Trapezoidal Rule

Computer scientists rarely integrate by hand. They use algorithms like the Trapezoidal Rule, which fits a line (trapezoid) between points instead of a flat rectangle. This usually converges much faster.

python
1import numpy as np
2 
3def f(x): return np.exp(-x**2) # The Gaussian bell curve
4 
5a, b = 0, 1
6n = 5
7h = (b - a) / n
8 
9x = np.linspace(a, b, n + 1)
10y = f(x)
11 
12# Trapezoidal rule: h/2 * (y0 + 2y1 + ... + yn)
13area = (h/2) * (y[0] + 2 * np.sum(y[1:-1]) + y[-1])
14 
15print(f"Estimated area under e^(-x^2) from 0 to 1: {area:.6f}")
16print("This is related to the Error Function (erf) used in Statistics.")

3. The Fundamental Theorem of Calculus (FTC)

The FTC states that integration and differentiation are inverse operations. If F(x)F(x) is the antiderivative of f(x)f(x), then: abf(x)dx=F(b)F(a)\int_a^b f(x) \, dx = F(b) - F(a)

This turns a hard problem of “infinite summing” into a simple problem of “subtraction.”

If velocity v(t) is the derivative of position s(t), what does the integral of v(t) represent?

4. Improper Integrals

Sometimes we need to integrate over an infinite interval, such as 0exdx\int_0^\infty e^{-x} \, dx. These are vital for calculating total energy or probabilities in bell curves.

Does the integral of 1/x from 1 to infinity converge?

5. Summary Check

Which numerical method is generally more accurate for the same number of steps?

Section Detail

Laplace Transforms

Laplace Transforms

The Laplace Transform is a powerful tool used in engineering and physics to solve linear differential equations. Its primary “trick” is to transform a function from the Time Domain (tt) to the Complex Frequency Domain (ss), where integration and differentiation become simple algebraic multiplication and division.

The Definition

The Laplace transform of a function f(t)f(t) is defined as:

L{f(t)}=F(s)=0estf(t)dt\mathcal{L}\{f(t)\} = F(s) = \int_0^\infty e^{-st} f(t) dt

Why Transform?

In the time domain, a system might be described by a messy differential equation: ad2ydt2+bdydt+cy=f(t)a \frac{d^2y}{dt^2} + b \frac{dy}{dt} + cy = f(t)

In the Laplace (s) domain, this becomes a simple equation: (as2+bs+c)Y(s)=F(s)(as^2 + bs + c)Y(s) = F(s)

You can then solve for Y(s)Y(s) using basic algebra and “Inverse Transform” back to the time domain.

Transfer Functions and Stability

In control theory, the Transfer Function H(s)=Y(s)X(s)H(s) = \frac{Y(s)}{X(s)} describes how a system responds to an input.

  • If the “poles” (the values of ss that make the denominator zero) have negative real parts, the system is Stable (vibrations die down).
  • If any pole has a positive real part, the system is Unstable (vibrations grow until the system breaks).
python
1import sympy as sp
2 
3# Define symbols
4t, s = sp.symbols('t s')
5# Define a function to transform: sin(t)
6f = sp.sin(t)
7 
8# Calculate Laplace Transform
9F = sp.laplace_transform(f, t, s)
10 
11print(f"Time Domain: f(t) = {f}")
12print(f"S-Domain (Laplace): F(s) = {F[0]}")
13print("\nNotice how the trigonometric function became a rational algebraic fraction.")
14 

Use Cases

  1. Circuit Analysis: Capacitors and Inductors become simple algebraic impedances (1/sC1/sC and sLsL).
  2. Control Systems: Tuning a thermostat or a drone’s flight controller.
  3. Signal Processing: Filtering noise out of audio or sensor data.

Exercises

What is the primary advantage of moving from the time domain to the s-domain?

In a transfer function, if a system has a 'Pole' at s = +5, what does it mean for the system's stability?

The Laplace transform is specifically useful for systems that are:

Section Detail

Limits and Continuity

Limits and Continuity

Calculus is built on the concept of change over zero. To make sense of “instantaneous” change, we need a way to talk about what a function does as it gets closer and closer to a point, even if it never actually reaches it. This is the Limit.

1. The Epsilon-Delta Definition

Intuition: A limit limxcf(x)=L\lim_{x \to c} f(x) = L means we can force f(x)f(x) to be as close to LL as we want (within ϵ\epsilon), just by making xx sufficiently close to cc (within δ\delta).

For every ϵ>0\epsilon > 0, there exists a δ>0\delta > 0 such that 0<xc<δ    f(x)L<ϵ0 < |x - c| < \delta \implies |f(x) - L| < \epsilon.

Let’s vizualize this. If f(x)=2xf(x) = 2x, and we want to be within ϵ=0.1\epsilon = 0.1 of the output L=4L=4 at x=2x=2, how close must xx be?

python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4def f(x): return 2 * x
5 
6c, L = 2, 4
7epsilon = 0.1
8delta = epsilon / 2 # For f(x)=2x, delta is exactly epsilon/2
9 
10x = np.linspace(c - 2*delta, c + 2*delta, 500)
11y = f(x)
12 
13plt.plot(x, y, label='f(x)=2x')
14plt.axhline(L + epsilon, color='r', linestyle='--', label='L + ε')
15plt.axhline(L - epsilon, color='r', linestyle='--', label='L - ε')
16plt.axvline(c + delta, color='g', linestyle='--', label='c + δ')
17plt.axvline(c - delta, color='g', linestyle='--', label='c - δ')
18 
19plt.fill_between([c-delta, c+delta], L-epsilon, L+epsilon, color='yellow', alpha=0.3, label='Safe Zone')
20plt.legend()
21plt.title("The Epsilon-Delta Game")
22plt.show()

2. When Limits Fail

A limit only exists if it matches from both directions. If the “safe zone” can’t be established because the function jumps or oscillates, the limit does not exist.

Consider f(x) = sin(1/x) near x=0. Why does the limit as x -> 0 DNE?

3. Continuity: The Glue of Calculus

A function is continuous at cc if the limit exists and exactly matches the function’s value: limxcf(x)=f(c)\lim_{x \to c} f(x) = f(c).

Let’s test for a “Broken” function: f(x)={x2x<12x=1xx>1f(x) = \begin{cases} x^2 & x < 1 \\ 2 & x = 1 \\ x & x > 1 \end{cases}

python
1import numpy as np
2 
3def f(x):
4 if x < 1: return x**2
5 if x == 1: return 2
6 return x
7 
8# Check limit from left and right
9left_lim = f(0.999999)
10right_lim = f(1.000001)
11value = f(1.0)
12 
13print(f"Limit from left: {left_lim}")
14print(f"Limit from right: {right_lim}")
15print(f"Actual value at 1: {value}")
16 
17is_continuous = np.isclose(left_lim, right_lim) and np.isclose(left_lim, value)
18print(f"Is continuous? {is_continuous}")

4. The Intermediate Value Theorem (IVT)

If ff is continuous on [a,b][a, b], it must hit every value between f(a)f(a) and f(b)f(b). This is why we can use the Bisection Method to find roots.

If f(x) is continuous and f(1) = -5 and f(2) = 5, must there be a zero in (1, 2)?

5. Summary Check

Which is a 'stronger' condition (if A holds, B must hold)?

Section Detail

Mean Value Theorem: The Guarantee of Speed

Mean Value Theorem: The Guarantee of Speed

The Mean Value Theorem (MVT) is often viewed as a “theoretical” result used by mathematicians for proofs. However, it has a very intuitive and practical meaning: if you travel 100 miles in one hour, there must have been at least one instant where your speedometer read exactly 100 mph.

Rolle’s Theorem: The Foundation

Rolle’s Theorem is a special case of the MVT. It states that if a continuous and differentiable function f(x)f(x) starts and ends at the same value (f(a)=f(b)f(a) = f(b)), there must be at least one point cc in between where the derivative is zero (f(c)=0f'(c) = 0).

Think of it like this: if you throw a ball up and it comes back to your hand, there was a moment at the very top of its path where its vertical velocity was exactly zero.

The General Mean Value Theorem

The MVT generalizes Rolle’s Theorem to functions that don’t end where they start. It states that for a differentiable function f(x)f(x) on [a,b][a, b], there exists a point c(a,b)c \in (a, b) such that: f(c)=f(b)f(a)baf'(c) = \frac{f(b) - f(a)}{b - a}

In plain English: The instantaneous rate of change (f(c)f'(c)) must equal the average rate of change over the interval at some point.

Why do we care?

The MVT is the bridge between local behavior (the derivative at a point) and global behavior (the function values at the endpoints).

  • It allows us to bound the error in numerical approximations.
  • It proves that if f(x)=0f'(x) = 0 everywhere, f(x)f(x) must be a constant.
  • It is the primary tool used to prove the Fundamental Theorem of Calculus.
python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4# Interval [a, b]
5a, b = 0, 2
6 
7# Function f(x) = x^2
8def f(x): return x**2
9def df(x): return 2*x
10 
11# Average rate of change (Secant slope)
12avg_rate = (f(b) - f(a)) / (b - a)
13 
14# Find 'c' where f'(c) == avg_rate => 2c = 2 => c = 1
15c = 1
16 
17x = np.linspace(-0.5, 2.5, 100)
18plt.plot(x, f(x), label='f(x) = x^2')
19plt.plot([a, b], [f(a), f(b)], '--', color='red', label='Average Rate (Secant)')
20plt.scatter([c], [f(c)], color='green', zorder=5)
21 
22# Tangent at c
23tangent_x = np.linspace(0.5, 1.5, 50)
24tangent_y = f(c) + df(c)*(tangent_x - c)
25plt.plot(tangent_x, tangent_y, color='green', label='Instantaneous Rate (Tangent)')
26 
27plt.title("Mean Value Theorem: Parallel Slopes")
28plt.legend()
29plt.grid(True)
30plt.show()
31 
32print(f"Average Rate over [{a}, {b}]: {avg_rate}")
33print(f"Instantaneous Rate at c={c}: {df(c)}")
34 

Taylor’s Theorem: MVT on Steroids

If the MVT tells us how to approximate a function with a line, Taylor’s Theorem tells us how to approximate it with a polynomial of any degree. f(x)=f(a)+f(a)(xa)+f(a)2!(xa)2++Rn(x)f(x) = f(a) + f'(a)(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \dots + R_n(x) The “remainder” Rn(x)R_n(x) is defined using a generalization of the Mean Value Theorem. This allows engineers to know exactly how many terms they need to keep in a computer simulation to ensure the error remains below a certain threshold.

Exercises

If a driver passes two toll booths 60 miles apart in 45 minutes, can they be fined for speeding in a 65 mph zone?

What condition must be met for the Mean Value Theorem to apply to a function on [a, b]?

How is Rolle's Theorem related to the Mean Value Theorem?

Section Detail

Multiple Integration

Multiple Integration

In 1D calculus, we integrate over a line to find an area. In Multivariable Calculus, we integrate over a 2D region (Double Integral) to find a volume, or over a 3D region (Triple Integral) to find a total mass or charge.

Double Integrals: Volumes under Surfaces

The integral Rf(x,y)dA\iint_R f(x, y) dA represents the volume between the xyxy-plane and the surface z=f(x,y)z = f(x, y) over the region RR.

Fubini’s Theorem: If the function is nice, you can calculate the double integral by doing two “nested” single integrals in any order: abcdf(x,y)dydx=cdabf(x,y)dxdy\int_a^b \int_c^d f(x, y) dy \, dx = \int_c^d \int_a^b f(x, y) dx \, dy

The Jacobian: Scaling Space

When we change variables (e.g., from Cartesian (x,y)(x, y) to Polar (r,θ)(r, \theta)), the “infinitesimal area” dAdA changes. We use the Jacobian to account for this stretching.

  • Cartesian: dA=dxdydA = dx \, dy
  • Polar: dA=rdrdθdA = r \, dr \, d\theta

If you forget the rr in polar coordinates, your areas and volumes will be wrong!

python
1from scipy import integrate
2import numpy as np
3 
4# Let's calculate the volume of a hemisphere of radius 1
5# Surface: z = sqrt(1 - x^2 - y^2)
6# We will use SciPy to integrate over a circular region
7 
8def f(y, x):
9 if x**2 + y**2 <= 1:
10 return np.sqrt(1 - x**2 - y**2)
11 return 0
12 
13# Integrate over the square [-1, 1] x [-1, 1]
14# Note: we filter outside the circle in the function f
15volume, error = integrate.dblquad(f, -1, 1, lambda x: -1, lambda x: 1)
16 
17print(f"Calculated Volume: {volume:.4f}")
18print(f"Theoretical (2/3 * pi): { (2/3) * np.pi:.4f}")
19 

Triple Integrals and Density

If ρ(x,y,z)\rho(x, y, z) represents the density of an object at point (x,y,z)(x, y, z), the total mass of the object is the triple integral of the density over its volume VV:

M=Vρ(x,y,z)dVM = \iiint_V \rho(x, y, z) dV

Exercises

When integrating in polar coordinates, why do we include an extra 'r' factor?

What does Fubini's Theorem allow us to do?

If the density of a cube is constant ($\rho = 1$), what is the triple integral of $\rho$ over the cube's volume equal to?

Section Detail

Multivariable Calculus

Multivariable Calculus

Multivariable calculus extends the concepts of single-variable calculus to functions of several variables.

Partial Derivatives and the Gradient

A partial derivative measures the rate of change of a multivariable function with respect to one variable, holding others constant. The Gradient f\nabla f is a vector of partial derivatives: f=(fx1,fx2,,fxn)\nabla f = \left( \frac{\partial f}{\partial x_1}, \frac{\partial f}{\partial x_2}, \dots, \frac{\partial f}{\partial x_n} \right) It points in the direction of the steepest ascent.

python
1def f(x, y):
2 return x**2 + 3*y**2
3 
4def gradient_f(x, y):
5 # Partial w.r.t x: 2x
6 # Partial w.r.t y: 6y
7 return (2*x, 6*y)
8 
9x0, y0 = 1.0, 2.0
10grad = gradient_f(x0, y0)
11print(f"Gradient at ({x0}, {y0}): {grad}")

Multiple Integrals

A double integral Df(x,y)dA\iint_D f(x, y) \, dA calculates the volume under the surface z=f(x,y)z = f(x, y) over a region DD in the xyxy-plane.

python
1from scipy.integrate import dblquad
2 
3# f(x, y) = x*y
4# Over [0, 1] x [0, 2]
5area, error = dblquad(lambda y, x: x*y, 0, 1, lambda x: 0, lambda x: 2)
6 
7print(f"Double integral of x*y over [0,1]x[0,2]: {area:.4f}")

If the partial derivative of f with respect to x is zero everywhere, what can we say about f?

Vector Fields and Line Integrals

A vector field F\mathbf{F} assigns a vector to every point in space. A line integral CFdr\int_C \mathbf{F} \cdot d\mathbf{r} measures the work done by a force field along a path CC.

What is a conservative vector field?

The Jacobian Matrix

The Jacobian matrix of a vector-valued function f:RnRm\mathbf{f}: \mathbb{R}^n \to \mathbb{R}^m is the matrix of all first-order partial derivatives. It represents the best linear approximation of the function near a point. Jij=fixjJ_{ij} = \frac{\partial f_i}{\partial x_j}

Section Detail

Mathematical Optimization

Mathematical Optimization

Optimization is the selection of a best element (with regard to some criterion) from some set of available alternatives. In its simplest form, this means finding the values that maximize or minimize a function.

Unconstrained Optimization

For a differentiable function f(x)f(x), local extrema occur at points where f(x)=0f'(x) = 0. The Second Derivative Test determines if a point is a maximum (f<0f'' < 0) or a minimum (f>0f'' > 0).

python
1import numpy as np
2 
3def f(x):
4 return x**4 - 4*x**2 + 3
5 
6def df(x):
7 return 4*x**3 - 8*x
8 
9def ddf(x):
10 return 12*x**2 - 8
11 
12# Roots of df(x) are 0, sqrt(2), -sqrt(2)
13critical_points = [0, np.sqrt(2), -np.sqrt(2)]
14 
15for p in critical_points:
16 second_der = ddf(p)
17 kind = "Min" if second_der > 0 else "Max"
18 print(f"Point x={p:.2f} is a {kind} (f''={second_der:.2f})")

Gradient Descent

In higher dimensions, we often use iterative methods like Gradient Descent to find a local minimum: xn+1=xnγf(xn)\mathbf{x}_{n+1} = \mathbf{x}_n - \gamma \nabla f(\mathbf{x}_n) where γ\gamma is the learning rate.

python
1def f(x, y):
2 return x**2 + y**2 + 10
3 
4def grad_f(x, y):
5 return np.array([2*x, 2*y])
6 
7point = np.array([5.0, 5.0])
8gamma = 0.1
9 
10for _ in range(10):
11 point = point - gamma * grad_f(*point)
12 print(f"Current point: {point}")

If the gradient of a function at a point is (0,0,0), what can we conclude?

Constrained Optimization: Lagrange Multipliers

To optimize f(x,y)f(x, y) subject to g(x,y)=cg(x, y) = c, we look for points where the gradients are parallel: f=λg\nabla f = \lambda \nabla g

What does the Lagrange multiplier lambda represent in economic contexts?

Section Detail

Partial Differential Equations

Partial Differential Equations (PDEs)

Ordinary Differential Equations (ODEs) deal with functions of one variable (usually time). Partial Differential Equations (PDEs) deal with functions of multiple variables, such as the temperature u(x,t)u(x, t) at a position xx and time tt.

The Mother of All PDEs: The Laplacian

Most physical PDEs involve the Laplacian (2u=Δu\nabla^2 u = \Delta u), which is the divergence of the gradient (u\nabla \cdot \nabla u). In 1D, this is just uxxu_{xx} (the second spatial derivative). It measures how much the value at a point differs from the average of its neighbors.

Three Classic PDEs

1. The Heat Equation (Diffusion)

ut=α2uu_t = \alpha \nabla^2 u Meaning: The rate of change in temperature (utu_t) is proportional to how much “different” a point is from its neighbors. Heat flows from hot to cold to “smooth out” the distribution.

2. The Wave Equation

utt=c22uu_{tt} = c^2 \nabla^2 u Meaning: Acceleration (uttu_{tt}) is proportional to the local “curvature” of the medium. This models everything from guitar strings to light waves.

3. Laplace’s Equation (Equilibrium)

2u=0\nabla^2 u = 0 Meaning: The system has reached a state where every point is the average of its neighbors. This describes electric potentials in vacuum or the steady-state temperature of a plate.

Numerical Solution: The Finite Difference Method

Solving PDEs analytically is hard. Engineers use the Finite Difference Method, which replaces derivatives with differences on a grid.

python
1import numpy as np
2 
3# Simulate 1D Heat Diffusion in a rod
4L = 1.0 # Length
5nx = 50 # Number of points
6dx = L / (nx - 1)
7alpha = 0.01 # Thermal diffusivity
8dt = 0.001 # Time step
9 
10# Initial condition: hot spot in the middle
11u = np.zeros(nx)
12u[int(0.4*nx):int(0.6*nx)] = 100.0
13 
14# Time loop: simplified explicit scheme
15for _ in range(100):
16 u_new = u.copy()
17 for i in range(1, nx-1):
18 # u_t = alpha * u_xx
19 u_new[i] = u[i] + alpha * dt / dx**2 * (u[i+1] - 2*u[i] + u[i-1])
20 u = u_new
21 
22print(f"Temperature at middle: {u[nx//2]:.2f}")
23print("The heat has started to spread from the center to the edges.")
24 

Exercises

If a function satisfies Laplace's Equation ($\nabla^2 u = 0$), what can be said about its local behavior?

In the Heat Equation ($u_t = \alpha u_{xx}$), what happens if the second derivative $u_{xx}$ is positive?

Why are PDEs harder to solve than ODEs?

Section Detail

Sequences and Series

Sequences and Series

Calculus is the study of the infinite. While derivatives and integrals use infinite processes to find slopes and areas, sequences and series study infinite processes directly. How can you add up an infinite number of things and get a finite answer? This question is at the heart of Zeno’s paradoxes and modern data compression.

Limits of Sequences

A sequence is an infinite list of numbers a1,a2,a3,a_1, a_2, a_3, \dots. We are interested in its convergence: does the sequence eventually settle down to a specific value LL? limnan=L\lim_{n \to \infty} a_n = L

In computer science, every iterative algorithm (like Newton’s method or Gradient Descent) is a sequence. We need to prove that these sequences converge to the correct solution.

Infinite Series: Summing to Infinity

A series is the sum of the terms of a sequence: n=1an\sum_{n=1}^\infty a_n. A series converges if the sequence of its partial sums Sn=a1++anS_n = a_1 + \dots + a_n converges to a finite limit.

The Geometric Series

The most famous convergent series is the geometric series: 1+r+r2+r3+=11rfor r<11 + r + r^2 + r^3 + \dots = \frac{1}{1-r} \quad \text{for } |r| < 1 This formula is used to calculate the “Present Value” of future cash flows in finance and the “Multiplier Effect” in economics.

Taylor Series: Polynomials for Everything

The ultimate application of series is the Taylor Series. It allows us to represent transcendental functions (ex,sinx,lnxe^x, \sin x, \ln x) as infinite polynomials. f(x)=n=0f(n)(a)n!(xa)nf(x) = \sum_{n=0}^\infty \frac{f^{(n)}(a)}{n!}(x-a)^n

This is how calculators and computers compute sin(1)\sin(1). They don’t have a giant lookup table; they use the first few terms of the Taylor series to get as much precision as needed.

python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4def taylor_exp(x, n):
5 """Approximate e^x using first n terms of Taylor series at a=0."""
6 approx = 0
7 factorial = 1
8 for i in range(n):
9 if i > 0: factorial *= i
10 approx += (x**i) / factorial
11 return approx
12 
13x_val = 1.0
14print(f"Exact e^{x_val}: {np.exp(x_val)}")
15for n in [1, 3, 5, 10]:
16 print(f"Taylor (n={n}): {taylor_exp(x_val, n)}")
17 
18# Visualizing approximation
19x = np.linspace(-2, 2, 100)
20plt.plot(x, np.exp(x), 'k', label='Exact exp(x)')
21plt.plot(x, taylor_exp(x, 3), '--', label='n=3 Approximation')
22plt.plot(x, taylor_exp(x, 5), ':', label='n=5 Approximation')
23plt.ylim(-1, 8)
24plt.legend()
25plt.title("Taylor Expansion of e^x")
26plt.grid(True)
27plt.show()
28 

Power Series and Convergence

A Power Series cnxn\sum c_n x^n only converges for xx within a certain “Radius of Convergence.” Outside this range, the series explodes to infinity. Knowing this limit is vital for ensuring the stability of electronic filters and signal processing algorithms.

Exercises

Does the series 1 + 1/2 + 1/4 + 1/8 + ... converge? If so, to what?

Why is the Taylor series of sin(x) particularly efficient for computers?

What happens to a power series outside its radius of convergence?

Section Detail

The Fundamental Theorems of Vector Calculus

The Fundamental Theorems

In 1D, the Fundamental Theorem of Calculus says that the integral of a derivative over an interval is determined by the values at the endpoints. Vector calculus extends this beautiful idea to higher dimensions: the behavior of a field inside a region is determined entirely by the field on its boundary.

Green’s Theorem (2D)

Green’s Theorem relates a line integral around a closed curve CC to a double integral over the region DD enclosed by CC.

C(Pdx+Qdy)=D(QxPy)dA\oint_C (P dx + Q dy) = \iint_D \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) dA

In physical terms: the total “circulation” around the boundary equals the sum of all the tiny “curls” inside.

Stokes’ Theorem (3D)

Stokes’ Theorem is the 3D generalization of Green’s Theorem. It relates the surface integral of the curl of a vector field over a surface SS to the line integral of the field around the boundary curve CC.

S(×F)dS=CFdr\iint_S (\nabla \times \mathbf{F}) \cdot d\mathbf{S} = \oint_C \mathbf{F} \cdot d\mathbf{r}

This is why, in a conservative field (where ×F=0\nabla \times \mathbf{F} = 0), the line integral around any closed loop is zero.

Gauss’ (Divergence) Theorem

The Divergence Theorem relates the volume integral of the divergence of a field to the net “flux” through the surface enclosing that volume.

V(F)dV=SFdS\iiint_V (\nabla \cdot \mathbf{F}) dV = \iint_S \mathbf{F} \cdot d\mathbf{S}

If there is a net flow of water coming out of a balloon, there must be a source of water (positive divergence) inside the balloon.

python
1import numpy as np
2 
3# Calculating flux through a unit sphere (Gauss Theorem)
4# Field F = [x, y, z] -> Divergence is 1 + 1 + 1 = 3
5# Volume of unit sphere = 4/3 * pi
6 
7div_F = 3
8volume = (4/3) * np.pi
9theoretical_flux = div_F * volume
10 
11print(f"Total outward flux: {theoretical_flux:.4f}")
12print("Instead of a hard surface integral, we used a simple volume integral!")
13 

Why These Matter

These theorems are the foundation of modern physics. Maxwell’s Equations (Electromagnetism), Fluid Dynamics (Navier-Stokes), and General Relativity all rely on the relationship between local changes (derivatives) and global accumulation (integrals).

Exercises

According to the Divergence Theorem, if a region contains no sources or sinks ($\nabla \cdot F = 0$), what is the net flux through its boundary?

Stokes' Theorem relates which two types of integrals?

If you want to calculate the work done by a force along a messy, jagged path, and you know the force is conservative, what is the best strategy?

Section Detail

Systems of ODEs

Systems of ODEs

Many physical systems involve multiple variables that change simultaneously, leading to coupled systems of differential equations.

Linear Systems with Constant Coefficients

A first-order linear system has the form: x(t)=Ax(t)\mathbf{x}'(t) = \mathbf{A}\mathbf{x}(t) where A\mathbf{A} is a constant matrix. If A\mathbf{A} has eigenvalues λi\lambda_i and eigenvectors vi\mathbf{v}_i, the general solution is: x(t)=cieλitvi\mathbf{x}(t) = \sum c_i e^{\lambda_i t} \mathbf{v}_i

python
1import numpy as np
2 
3# System: dx/dt = x + y, dy/dt = 4x + y
4A = np.array([[1, 1], [4, 1]])
5 
6eigenvalues, eigenvectors = np.linalg.eig(A)
7 
8print("Eigenvalues:", eigenvalues)
9print("Eigenvectors:\n", eigenvectors)
10 
11# Solution components involve exp(3t) and exp(-t)

Phase Plane Analysis

The behavior of the system near equilibrium points (where x=0\mathbf{x}' = 0) can be classified by the eigenvalues:

  • Sink (Stable node): All eigenvalues real and negative.
  • Source (Unstable node): All eigenvalues real and positive.
  • Saddle Point: Real eigenvalues of opposite signs.
  • Center: Purely imaginary eigenvalues.
  • Spiral: Complex eigenvalues with non-zero real part.

If the eigenvalues of a 2x2 system are -2 and -5, what is the stability of the origin?

Numerical Integration (Runge-Kutta)

For non-linear systems or those without analytical solutions, we use numerical methods like the 4th-order Runge-Kutta (RK4).

python
1def rk4_step(f, x, dt):
2 k1 = f(x)
3 k2 = f(x + 0.5 * dt * k1)
4 k3 = f(x + 0.5 * dt * k2)
5 k4 = f(x + dt * k3)
6 return x + (dt / 6.0) * (k1 + 2*k2 + 2*k3 + k4)
7 
8# Predator-Prey (Lotka-Volterra)
9def lotka_volterra(state):
10 x, y = state
11 a, b, c, d = 1.0, 0.1, 1.5, 0.75
12 return np.array([a*x - b*x*y, -c*y + d*x*y])
13 
14state = np.array([10.0, 5.0]) # Initial populations
15dt = 0.1
16for _ in range(5):
17 state = rk4_step(lotka_volterra, state, dt)
18 print(f"Populations: {state}")

What is a limit cycle in the context of phase plane analysis?

Section Detail

Taylor and Power Series

Taylor and Power Series

A Taylor series is an infinite sum of terms that are expressed in terms of the function’s derivatives at a single point.

Taylor’s Formula

The Taylor series of a real or complex-valued function f(x)f(x) that is infinitely differentiable at a real or complex number aa is the power series: f(x)=f(a)+f(a)1!(xa)+f(a)2!(xa)2+f(x) = f(a) + \frac{f'(a)}{1!}(x-a) + \frac{f''(a)}{2!}(x-a)^2 + \dots

python
1import numpy as np
2 
3def sin_taylor(x, n_terms):
4 res = 0
5 for n in range(n_terms):
6 sign = (-1)**n
7 term = (x**(2*n + 1)) / np.math.factorial(2*n + 1)
8 res += sign * term
9 return res
10 
11x_val = np.pi / 4 # 45 degrees
12print(f"sin(pi/4) exact: {np.sin(x_val):.6f}")
13print(f"Taylor (1 term): {sin_taylor(x_val, 1):.6f}")
14print(f"Taylor (3 terms): {sin_taylor(x_val, 3):.6f}")

Radius of Convergence

A power series an(xa)n\sum a_n (x-a)^n has a radius of convergence RR such that the series converges absolutely for xa<R|x-a| < R and diverges for xa>R|x-a| > R.

What is the Taylor series of exp(x) centered at 0?

Remainder Term: Taylor’s Theorem

Taylor’s Theorem gives an estimate of the error when a function is approximated by its nn-th degree Taylor polynomial. The Lagrange form of the remainder is: Rn(x)=f(n+1)(c)(n+1)!(xa)(n+1)R_n(x) = \frac{f^{(n+1)}(c)}{(n+1)!}(x-a)^{(n+1)} for some cc between aa and xx.

python
1def exp_error_estimate(x, n):
2 import math
3 # Error for exp(x) is x^(n+1)/(n+1)! * exp(c)
4 # where c is in [0, x]. Max error at c=x.
5 return (abs(x)**(n+1) / math.factorial(n+1)) * math.exp(abs(x))
6 
7print(f"Max error for exp(1) with 5 terms: {exp_error_estimate(1, 5):.6f}")

Can any infinitely differentiable function be represented exactly by its Taylor series everywhere?

Section Detail

Vector Fields

Vector Fields

In single-variable calculus, we map a number to a number (xyx \to y). In Vector Calculus, we map a position to a vector (rV\mathbf{r} \to \mathbf{V}). This represents physical phenomena like wind speed at every point in a city, or the force of gravity at every point in the solar system.

The Gradient: The Direction of Maximum Ascent

Given a scalar field f(x,y)f(x, y) (like the altitude of a mountain), the Gradient f\nabla f is a vector field that points in the direction of the steepest uphill slope.

f=(fx,fy)\nabla f = \left( \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y} \right)

The magnitude of the gradient tells you how steep the slope is.

Divergence: Sources and Sinks

The Divergence (V\nabla \cdot \mathbf{V}) of a vector field measures how much the “fluid” is expanding or compressing at a point.

  • Positive Divergence: The point is a Source (fluid is created/flowing out).
  • Negative Divergence: The point is a Sink (fluid is destroyed/flowing in).

Curl: The Rotation of the Field

The Curl (×V\nabla \times \mathbf{V}) measures the tendency of the field to rotate around a point. If you placed a tiny paddlewheel in the field, the curl tells you how fast and in what direction it would spin.

python
1import numpy as np
2import matplotlib.pyplot as plt
3 
4# Define a grid of points
5x, y = np.meshgrid(np.linspace(-2, 2, 10), np.linspace(-2, 2, 10))
6 
7# Example Vector Field: Rotational field (V = [-y, x])
8u = -y
9v = x
10 
11print("Visualizing a rotational field (Curl > 0):")
12# In a real environment, we'd use plt.quiver(x, y, u, v)
13# For now, let's look at the vectors at a few points
14for i in [0, 5, 9]:
15 for j in [0, 5, 9]:
16 print(f"Point ({x[i,j]:.1f}, {y[i,j]:.1f}) -> Vector ({u[i,j]:.1f}, {v[i,j]:.1f})")
17 

Conservative Fields

A vector field is Conservative if it is the gradient of some scalar function (V=fV = \nabla f). In physics, this means the work done moving between two points is independent of the path taken. Gravity and electric fields are conservative; friction is not.

Exercises

If the Divergence of a wind field at a certain point is zero, what does it mean?

What does the Curl of a field represent?

Why is the Gradient important in Machine Learning?