Contents
Deep Breakdown
What it tells me (Situation Awareness): The derivative of cosine is negative sine. The negative sign reflects that cosine decreases where sine is positive (on : cosine decreases from 1 to 0 while sine is positive). Together with , these two rules drive the complete 4-step differentiation cycle. In DA/DS: used whenever a model contains cosine terms — transformer positional encodings use both and components; Fourier series include terms; random Fourier features for kernel approximation combine and ; time series seasonal decomposition uses both.
Flowchart
Real-world use
Where it is used
Transformer positional encoding odd dimensions (); gradient backprop through cosine features; kernel SVM with random Fourier features ( where uses ); decomposing time series with additive seasonal cosine terms.
Problem it solves
Differentiating any function involving cosine — including gradient computation through cosine-based positional encodings and Fourier feature maps — requires .
How it solves the problem
From first principles: . Using : the limit is .
Example in a business
A DS builds a time series model with explicit seasonal component: . Gradient w.r.t. : . Gradient w.r.t. time (for forecasting horizon optimization): — uses both and .
The formula, piece by piece
- : cosine; period ; even function (); range
- : derivative; the negative sign distinguishes it from
- Mnemonic: "Co-functions differentiate to the other with a sign flip for cos": ,
- Chain rule:
- Examples: ;
- Second derivative: ; so (same ODE as sine)
- Relationship to sine: ; differentiating: .
The formula in words
"The slope of the cosine curve at any point equals the negative sine value at that point. At the top of the cosine wave (, ), the slope is zero (sine is zero). As the cosine falls (), the slope is negative (sine is positive)." Tiny examples: (flat top of cosine wave). (steepest descent of cosine). .
Critical Concepts
- Sine-cosine symmetry: and . The pair is related by the identity and . Differentiating shifts phase by .
- Even/odd function preservation under differentiation: is even (), is odd. Derivative of an even function is odd: (odd). Derivative of odd is even: (even).
- Product rule with sin/cos: (use product rule). This identity arises in Fourier series manipulation.
- Random Fourier features gradient: ; ; used in training kernel approximation models.
Step-by-step calculation (tiny example)
Differentiate .
Step 1: First term — chain rule: .
Step 2: Second term — ; power rule + chain rule: .
Step 3: Combine: .
Code examples
Beginner example (Python)
import numpy as np
def cosine_deriv(x: float) -> float:
"""d/dx(cos(x)) = -sin(x)."""
return -np.sin(x)
# Numerical verification
x_vals = np.linspace(0, 2 * np.pi, 9)
h = 1e-7
print(f"{'x (rad)':>10} {'-sin(x)':>10} {'numerical':>12} {'match':>7}")
for x in x_vals:
analytic = cosine_deriv(x)
numerical = (np.cos(x + h) - np.cos(x - h)) / (2 * h)
match = abs(analytic - numerical) < 1e-5
print(f"{x:>10.4f} {analytic:>10.5f} {numerical:>12.5f} {str(match):>7}")
# Random Fourier feature gradient
print("\n--- Random Fourier feature gradient ---")
np.random.seed(42)
d_in = 4
omega = np.random.randn(d_in) # random frequency vector
b = np.random.uniform(0, 2 * np.pi)
x = np.array([1.0, 0.5, -0.3, 0.8])
# phi(x) = cos(omega^T x + b)
phi = np.cos(omega @ x + b)
# d(phi)/dx = -sin(omega^T x + b) * omega
d_phi_dx = -np.sin(omega @ x + b) * omega
print(f"phi(x) = cos(omega^T x + b) = {phi:.5f}")
print(f"d(phi)/dx = -sin(omega^T x + b) * omega = {d_phi_dx}")Beginner example (R)
# d/dx(cos(x)) = -sin(x)
cosine_deriv <- function(x) -sin(x)
x_vals <- seq(0, 2 * pi, length.out = 9)
h <- 1e-7
cat(sprintf("%-10s %-10s %-12s\n", "x (rad)", "-sin(x)", "numerical"))
for (x in x_vals) {
analytic <- cosine_deriv(x)
numerical <- (cos(x + h) - cos(x - h)) / (2 * h)
cat(sprintf("%-10.4f %-10.5f %-12.5f\n", x, analytic, numerical))
}Professional example (Python)
import numpy as np
from sklearn.kernel_approximation import RBFSampler
from sklearn.preprocessing import StandardScaler
np.random.seed(42)
# -- Random Fourier Features: cosine derivative in kernel approximation --------
# RBF kernel k(x,z) = exp(-gamma*||x-z||^2)
# Approx: k(x,z) ~ phi(x)^T phi(z) where phi_j(x) = sqrt(2/D)*cos(omega_j^T x + b_j)
# Gradient of feature map phi_j w.r.t. input: -sqrt(2/D)*sin(omega_j^T x + b_j)*omega_j
N, D_IN, D_FEAT = 300, 5, 100
GAMMA = 0.5
X = np.random.randn(N, D_IN)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Sample random Fourier frequencies
omegas = np.random.randn(D_FEAT, D_IN) * np.sqrt(2 * GAMMA)
biases = np.random.uniform(0, 2 * np.pi, D_FEAT)
def rff_features(x: np.ndarray) -> np.ndarray:
"""Random Fourier features: phi(x) = sqrt(2/D) * cos(omega^T x + b)."""
projections = x @ omegas.T + biases[np.newaxis, :] # (N, D_FEAT)
return np.sqrt(2 / D_FEAT) * np.cos(projections)
def rff_gradient(x: np.ndarray) -> np.ndarray:
"""Gradient of RFF features: d phi_j/d x = -sqrt(2/D) * sin(omega_j^T x + b_j) * omega_j.
Uses d/dx(cos(f(x))) = -sin(f(x)) * f'(x).
"""
projections = x @ omegas.T + biases[np.newaxis, :] # (N, D_FEAT)
# d_phi_j / d_x_k = -sqrt(2/D) * sin(projection_j) * omega_j_k
coeffs = -np.sqrt(2 / D_FEAT) * np.sin(projections) # (N, D_FEAT)
# Sum over feature dimensions: (N, D_FEAT) @ (D_FEAT, D_IN) -> (N, D_IN)
return coeffs @ omegas
phi = rff_features(X_scaled)
d_phi = rff_gradient(X_scaled)
print("Random Fourier Features: d/dx(cos(x)) = -sin(x) in feature gradient")
print(f"RFF feature matrix shape: {phi.shape}")
print(f"Gradient matrix shape: {d_phi.shape} (d_phi/d_input for each sample)")
# Verify RBF kernel approximation quality
from sklearn.metrics.pairwise import rbf_kernel
K_exact = rbf_kernel(X_scaled[:50], X_scaled[:50], gamma=GAMMA)
K_approx = phi[:50] @ phi[:50].T
frobenius_error = np.linalg.norm(K_exact - K_approx, 'fro') / np.linalg.norm(K_exact, 'fro')
print(f"\nKernel approximation quality:")
print(f" Exact K range: [{K_exact.min():.3f}, {K_exact.max():.3f}]")
print(f" Approx K range: [{K_approx.min():.3f}, {K_approx.max():.3f}]")
print(f" Frobenius relative error: {frobenius_error:.4f}")
print(f"\nKey: phi gradient uses d/dx(cos(omega^T x + b)) = -sin(omega^T x + b) * omega")Source: 1300 p. 221