Contents
Deep Breakdown
What it tells me (Situation Awareness): The derivative of a constant is zero. A constant function has a flat graph — it never changes, so its instantaneous rate of change is 0 everywhere. This is the simplest differentiation rule, but it is used in every non-trivial differentiation: whenever a term in a function is a pure constant (a bias term, a regularization coefficient, a fixed parameter), its derivative vanishes. In DA/DS: bias terms in linear models (, ) do not contribute to the gradient with respect to inputs; constant regularization terms like in vanish when differentiating with respect to model inputs rather than weights; the constant rule is applied every time a partial derivative is taken, eliminating all terms that do not depend on the differentiation variable.
Flowchart
Real-world use
Where it is used
Computing gradients in linear regression ( for the bias when differentiating w.r.t. ); partial differentiation of multivariate functions; showing that adding a constant to a loss function does not change its gradient; deriving that the regularization coefficient is a constant multiplier in ; proving that the gradient of equals the gradient of for any constant .
Problem it solves
When differentiating a multivariate function, all terms not involving the differentiation variable become constants and vanish. Without the constant rule, every partial derivative computation would be unclear about what to do with irrelevant terms.
How it solves the problem
From first principles: . Taking the limit gives . Geometrically: a horizontal line has zero slope everywhere.
Example in a business
A DS differentiates the ridge regression loss with respect to specifically. The term is a constant with respect to : . This is the constant rule in action within a partial derivative. Every other weight's squared term vanishes, leaving only the -dependent terms.
The formula, piece by piece
- : any constant (a number that does not depend on )
- : the rate of change of a constant is always 0
- Proof: as
- Combined with sum rule:
- Combined with scalar rule: (when is not constant)
- In partial derivatives: for any not depending on
- In partial derivatives: when (different variable)
The formula in words
"The slope of a flat line is zero. Constants don't change, so their rate of change is zero. When you differentiate and encounter a term that has no in it, it disappears (contributes zero to the derivative)." Tiny examples: . . (not , but squared, a number). . ( is constant w.r.t. , so ).
Critical Concepts
- Constants vs constant multiples: but . The constant rule only applies to terms that are pure numbers, not to constants multiplying a function.
- Partial derivatives eliminate cross-terms: in , the terms and are constants with respect to and vanish. Result: . This is the backbone of gradient computation in multivariate optimization.
- Bias terms in neural networks: the bias in satisfies (bias vanishes from input gradient), but (bias is not constant w.r.t. itself). The constant rule applies only when the differentiation variable truly does not appear.
- Shifting a loss function: if for any constant , then . The gradient is identical. Shifting a loss by a constant does not affect optimization at all.
- Integration reversal: since , the constant of integration always appears in indefinite integrals: , because and satisfies for any .
Step-by-step calculation (tiny example)
Differentiate .
Step 1: Sum rule — differentiate each term separately.
Step 2: (power and scalar rule).
Step 3: (power and scalar rule: ).
Step 4: (constant rule).
Step 5: Combine. . At : .
Code examples
Beginner example (Python)
import numpy as np
def f(x: float, c: float = 7.0) -> float:
"""f(x) = 3x^2 + 2x + c. Derivative w.r.t. x is 6x + 2 (constant c vanishes)."""
return 3 * x**2 + 2 * x + c
def f_prime(x: float) -> float:
"""Analytic: d/dx(3x^2 + 2x + c) = 6x + 2. Constant c does not appear."""
return 6 * x + 2 # Show that gradient is the same regardless of constant c
h = 1e-7
x0 = 2.0
print("Constant rule: d/dx(f(x) + c) = d/dx(f(x)), regardless of c")
print(f"\nAt x={x0}, analytic f'(x) = {f_prime(x0)}")
print(f"\n{'c value':>10} {'Numerical grad':>16} {'Difference from analytic':>25}")
for c in [0.0, 7.0, -100.0, 1e6]:
f_c = lambda x, c=c: f(x, c)
numerical = (f_c(x0 + h) - f_c(x0 - h)) / (2 * h)
print(f"{c:>10.1f} {numerical:>16.8f} {abs(numerical - f_prime(x0)):>25.2e}")
print("\nKey: all numericals match. The constant c has no effect on the derivative.") # Partial derivative example: d/dw_1 of (w_1^2 + w_2^2)
w = np.array([3.0, 4.0])
grad_w1 = 2 * w[0] # constant rule: d/dw_1(w_2^2) = 0
grad_w2 = 2 * w[1] # constant rule: d/dw_2(w_1^2) = 0
print(f"\nPartial derivatives of w_1^2 + w_2^2 at w=[3,4]:")
print(f" d/dw_1 = 2*w_1 = {grad_w1} (w_2^2 term vanishes by constant rule)")
print(f" d/dw_2 = 2*w_2 = {grad_w2} (w_1^2 term vanishes by constant rule)")Beginner example (R)
# Constant rule: d/dx(c) = 0
f <- function(x, c = 7) 3*x^2 + 2*x + c
f_prime <- function(x) 6*x + 2 # c disappears
h <- 1e-7
x0 <- 2.0
cat("Constant rule: gradient is same for any constant c\n")
cat(sprintf("Analytic f'(%.1f) = %.4f\n\n", x0, f_prime(x0)))
cat(sprintf("%-10s %-16s %-20s\n", "c value", "Numerical grad", "Difference"))
for (c_val in c(0, 7, -100, 1e6)) { numerical <- (f(x0 + h, c_val) - f(x0 - h, c_val)) / (2 * h)
cat(sprintf("%-10.1f %-16.8f %-20.2e\n", c_val, numerical, abs(numerical - f_prime(x0))))
}Professional example (Python)
import numpy as np
from sklearn.datasets import make_regression
import functools
np.random.seed(42) # -- Constant rule in partial gradient: ridge regression --
# Demonstrates that d/dw_j of (lambda * w_k^2) = 0 for k != j.
N, D = 200, 4
X, y = make_regression(n_samples=N, n_features=D, noise=5.0, random_state=42)
LAMBDA = 0.1
def ridge_loss(w: np.ndarray, X: np.ndarray, y: np.ndarray, lam: float) -> float:
"""L(w) = (1/N) * ||y - Xw||^2 + lambda * ||w||^2."""
residuals = y - X @ w
return float(np.mean(residuals**2) + lam * np.dot(w, w))
def ridge_gradient(w: np.ndarray, X: np.ndarray, y: np.ndarray, lam: float) -> np.ndarray:
"""Gradient: dL/dw_j = (-2/N) * X_j^T * (y - Xw) + 2*lambda*w_j. Constant rule: d/dw_j(lambda * w_k^2) = 0 for k != j. Only the w_j^2 term survives the partial derivative. """
residuals = y - X @ w
return -2.0 / N * X.T @ residuals + 2.0 * lam * w
def numerical_gradient(loss_fn, w: np.ndarray, h: float = 1e-5) -> np.ndarray:
"""Numerical gradient via central differences."""
grad = np.zeros_like(w)
for i in range(len(w)):
w_plus = w.copy(); w_plus[i] += h
w_minus = w.copy(); w_minus[i] -= h
grad[i] = (loss_fn(w_plus) - loss_fn(w_minus)) / (2 * h)
return grad
w_test = np.random.randn(D) * 0.5
loss_fn = functools.partial(ridge_loss, X=X, y=y, lam=LAMBDA)
g_analytic = ridge_gradient(w_test, X, y, LAMBDA)
g_numeric = numerical_gradient(loss_fn, w_test)
print("Constant Rule in Partial Gradient: Ridge Regression")
print(f"\nLoss = (1/N)||y-Xw||^2 + lambda*||w||^2, lambda={LAMBDA}")
print(f"Gradient: dL/dw_j = (-2/N)*X_j^T*(y-Xw) + 2*lambda*w_j\n")
print(f"{'Param':>8} {'w_j':>8} {'Analytic':>14} {'Numerical':>14} {'Abs err':>12}")
for j in range(D):
print(f"{'w['+str(j)+']':>8} {w_test[j]:>8.4f} {g_analytic[j]:>14.8f} " f"{g_numeric[j]:>14.8f} {abs(g_analytic[j]-g_numeric[j]):>12.2e}") # Show that shifting loss by a constant does not change gradient
CONSTANT_SHIFT = 500.0
loss_fn_shifted = functools.partial( lambda w, X, y, lam, shift: ridge_loss(w, X, y, lam) + shift, X=X, y=y, lam=LAMBDA, shift=CONSTANT_SHIFT )
g_shifted = numerical_gradient(loss_fn_shifted, w_test)
max_diff = np.max(np.abs(g_analytic - g_shifted))
print(f"\nAdding constant {CONSTANT_SHIFT} to loss: max gradient change = {max_diff:.2e}")
print(f"Key: d/dw(L(w) + {CONSTANT_SHIFT}) = d/dw(L(w)). Constant disappears.")Source: 1300 p. 218