Contents
Deep Breakdown
What it tells me (Situation Awareness): The perfect cube expansion gives the full expansion of a cubed binomial. For addition: . For subtraction: (signs alternate: ). The coefficients are row 3 of Pascal's triangle, and correspond to . This is the special case of the binomial theorem . In DA/DS, this identity arises in: expanding polynomial features of degree 3 in feature engineering, deriving third-order Taylor approximations (), understanding the skewness of a distribution ( expansion), and simplifying cost function algebra that involves cubed differences. Note: this is the expansion identity; the factoring identity for is the separate sum/difference of cubes.
Flowchart
Real-world use
Where it is used
Third-order Taylor expansion: — when , the cubic expansion is exact. Skewness calculation: the third central moment , which is exactly expanded. Polynomial feature engineering: degree-3 feature expands into .
Problem it solves
Expanding by repeated FOIL is mechanical: first , then multiplying by again. The identity skips those steps and gives the result directly: . This is essential when deriving formulas that involve cubed differences, such as the third central moment of a distribution.
How it solves the problem
The coefficients come from for . The sign for the minus case follows the pattern : . Verified by multiplying: , then .
Example in a business
A data analyst computes the skewness of a revenue distribution. The third central moment requires . Expanding , taking expectations: . This allows computing skewness in a single pass over the data by accumulating , , and .
The formula, piece by piece
Breaking the notation:
- : a binomial raised to the third power.
- : first term — cubed, coefficient 1.
- : second term — coefficient , power of decreases by 1, power of increases by 1.
- : third term — coefficient .
- : last term — cubed, coefficient 1.
- For : substitute : signs alternate . Full expansions:
- Pascal's triangle row 3: — these are the coefficients for any binomial expansion. Skewness expansion: . TRAP: .
The two missing middle terms are substantial. The "sum of cubes" factoring identity is a completely different identity from the "cube of a sum" expansion .
The formula in words
" expands to . Coefficients: from Pascal's triangle row 3. Powers of decrease from 3 to 0; powers of increase from 0 to 3. For the minus case : replace with — signs alternate: . Never forget the middle terms: is NOT . In Python: (a + b)**3 == a**3 + 3*a**2*b + 3*a*b**2 + b**3 is always True."
Critical Concepts
- Coefficients : from Pascal's triangle row 3 (or for ). Memorize the pattern: the inner terms both have coefficient 3.
- TRAP: : the middle terms are often forgotten. This error appears frequently when computing cubed differences in statistical moments.
- Skewness formula: the third central moment expands via . Taking expectations gives the computational formula for skewness without needing to subtract the mean first.
- Minus case sign pattern: . Signs: . The odd-power terms (, and coefficient for ) flip; stays positive because .
- Distinguish from sum/difference of cubes: is an expansion of a cube. is a factoring target.
They are related: , but they are not the same thing.
Step-by-step calculation (tiny example)
Task: expand and evaluate at .
Step 1: Identify and , .
Step 2: Apply the expansion .
Step 3: Evaluate at .
Step 4: Verify directly .
Step 5: Verify the minus case — expand . At : .
Code examples
Beginner example (Python)
# Perfect cube expansion: (a ± b)³ = a³ ± 3a²b + 3ab² ± b³
def expand_cube_plus(a: float, b: float) -> float:
"""Return (a + b)³ using the explicit expansion."""
return a**3 + 3 * a**2 * b + 3 * a * b**2 + b**3
def expand_cube_minus(a: float, b: float) -> float:
"""Return (a - b)³ using the explicit expansion."""
return a**3 - 3 * a**2 * b + 3 * a * b**2 - b**3
# Verify against direct computation
pairs = [(2.0, 3.0), (5.0, 1.0), (-1.0, 4.0), (0.5, 0.25)]
print("Perfect cube expansion verification")
print(f"{'a':>6} {'b':>6} {'(a+b)³ direct':>14} {'expanded':>10} {'match':>6}")
for a, b in pairs:
direct = (a + b) ** 3
expanded = expand_cube_plus(a, b)
print(f"{a:>6.2f} {b:>6.2f} {direct:>14.4f} {expanded:>10.4f} {str(abs(direct - expanded) < 1e-10):>6}")
print(f"\n{'a':>6} {'b':>6} {'(a-b)³ direct':>14} {'expanded':>10} {'match':>6}")
for a, b in pairs:
direct = (a - b) ** 3
expanded = expand_cube_minus(a, b)
print(f"{a:>6.2f} {b:>6.2f} {direct:>14.4f} {expanded:>10.4f} {str(abs(direct - expanded) < 1e-10):>6}")
# TRAP: (a+b)³ ≠ a³ + b³
a, b = 2.0, 3.0
print(f"\nTRAP: (a+b)³ vs a³+b³ for a={a}, b={b}")
print(f" (a+b)³ = {(a+b)**3:.0f}")
print(f" a³ + b³ = {a**3 + b**3:.0f} (NOT the same!)")
print(f" Middle terms 3a²b + 3ab² = {3*a**2*b + 3*a*b**2:.0f}")
# Skewness: E[(X-μ)³] computational formula
import numpy as np
np.random.seed(42)
data = np.random.exponential(scale=2.0, size=1000) # right-skewed
mu = data.mean()
# Two methods
skew_direct = np.mean((data - mu) ** 3)
skew_expand = np.mean(data**3) - 3 * mu * np.mean(data**2) + 2 * mu**3
print(f"\nThird central moment (skewness numerator):")
print(f" E[(X-μ)³] direct: {skew_direct:.6f}")
print(f" E[(X-μ)³] formula: {skew_expand:.6f}")
print(f" Match: {abs(skew_direct - skew_expand) < 1e-8}")Beginner example (R)
# Perfect cube expansion in R
expand_cube_plus <- function(a, b) a^3 + 3*a^2*b + 3*a*b^2 + b^3
expand_cube_minus <- function(a, b) a^3 - 3*a^2*b + 3*a*b^2 - b^3
pairs <- list(c(2,3), c(5,1), c(-1,4), c(0.5,0.25))
cat("Plus case: (a+b)³\n")
cat(sprintf("%-6s %-6s %-14s %-10s %s\n", "a", "b", "(a+b)³ direct", "expanded", "match"))
for (p in pairs) {
a <- p[1]; b <- p[2]
direct <- (a + b)^3
expanded <- expand_cube_plus(a, b)
cat(sprintf("%-6.2f %-6.2f %-14.4f %-10.4f %s\n", a, b, direct, expanded, abs(direct - expanded) < 1e-10))
}
# Skewness via expansion
set.seed(42)
data <- rexp(1000, rate = 0.5) # right-skewed
mu <- mean(data)
skew_direct <- mean((data - mu)^3)
skew_expand <- mean(data^3) - 3 * mu * mean(data^2) + 2 * mu^3
cat(sprintf("\nThird central moment:\n"))
cat(sprintf(" Direct: %.6f\n", skew_direct))
cat(sprintf(" Formula: %.6f\n", skew_expand))
cat(sprintf(" Match: %s\n", abs(skew_direct - skew_expand) < 1e-8))Professional example (Python)
import numpy as np
import pandas as pd
# Scenario: single-pass skewness computation using (x - μ)³ expansion
# Accumulate sum_x, sum_x2, sum_x3 in one pass; compute 3rd central moment
# using the identity: E[(X-μ)³] = E[X³] - 3μE[X²] + 2μ³
class OnlineMomentsTracker:
"""
Single-pass tracker for the first three raw moments (E[X], E[X²], E[X³]).
Uses the cubic expansion to compute the third central moment
(skewness numerator) without a second pass over the data.
"""
def __init__(self) -> None:
self._n: int = 0
self._sum1: float = 0.0 # sum of x
self._sum2: float = 0.0 # sum of x²
self._sum3: float = 0.0 # sum of x³
def update(self, x: float) -> None:
"""Add one observation."""
self._n += 1
self._sum1 += x
self._sum2 += x * x
self._sum3 += x * x * x
@property
def mean(self) -> float:
"""E[X]."""
return self._sum1 / self._n if self._n > 0 else 0.0
@property
def variance(self) -> float:
"""E[X²] - (E[X])²."""
mu = self.mean
return self._sum2 / self._n - mu ** 2
@property
def third_central_moment(self) -> float:
"""
E[(X-μ)³] = E[X³] - 3μE[X²] + 2μ³.
Uses (a-b)³ expansion with a=X, b=μ, applied to expectations.
"""
mu = self.mean
ex2 = self._sum2 / self._n
ex3 = self._sum3 / self._n
return ex3 - 3 * mu * ex2 + 2 * mu ** 3
@property
def skewness(self) -> float:
"""Standardized skewness: third central moment / std³."""
std = self.variance ** 0.5
if std < 1e-12:
return 0.0
return self.third_central_moment / std ** 3
# Compare single-pass vs two-pass for multiple distributions
np.random.seed(42)
N = 10_000
distributions = {
"normal (0,1)": np.random.normal(0, 1, N),
"exponential (λ=1)": np.random.exponential(1, N),
"chi-squared (df=3)": np.random.chisquare(3, N),
}
rows = []
for dist_name, samples in distributions.items():
# Single-pass
tracker = OnlineMomentsTracker()
for x in samples:
tracker.update(float(x))
skew_single_pass = tracker.skewness
# Two-pass reference (numpy)
mu_ref = samples.mean()
std_ref = samples.std()
skew_ref = np.mean((samples - mu_ref) ** 3) / std_ref ** 3
rows.append({
"distribution": dist_name,
"skew_single": round(skew_single_pass, 6),
"skew_two_pass": round(skew_ref, 6),
"error": abs(skew_single_pass - skew_ref),
})
report = pd.DataFrame(rows)
print("Single-Pass Skewness via (x-μ)³ Expansion: E[(X-μ)³] = E[X³] - 3μE[X²] + 2μ³")
print("=" * 72)
print(report.to_string(index=False))
print(f"\nAll errors < 1e-6: {(report['error'] < 1e-6).all()}")Professional example (R)
# Single-pass skewness: E[(X-μ)³] = E[X³] - 3μE[X²] + 2μ³
set.seed(42)
N <- 10000
samples <- list(
"normal" = rnorm(N),
"exponential" = rexp(N),
"chisq" = rchisq(N, 3)
)
single_pass_skew <- function(x) {
n <- length(x)
sum_x <- sum(x); sum_x2 <- sum(x^2); sum_x3 <- sum(x^3)
mu <- sum_x / n
ex2 <- sum_x2 / n; ex3 <- sum_x3 / n
third_central <- ex3 - 3*mu*ex2 + 2*mu^3
std <- sqrt(ex2 - mu^2)
third_central / (std^3 + 1e-12)
}
report <- do.call(rbind, lapply(names(samples), function(nm) {
x <- samples[[nm]]
skew_s <- single_pass_skew(x)
skew_ref <- mean((x - mean(x))^3) / (sd(x)^3 + 1e-12)
data.frame(distribution = nm, skew_single = round(skew_s, 6),
skew_two_pass = round(skew_ref, 6), error = abs(skew_s - skew_ref))
}))
cat("Single-Pass Skewness via (x-μ)³ expansion\n")
print(report)Source: domain knowledge