Workspace IndexMath › Day 27

Differentiation, Gradients, and the Chain Rule TODO

Math · Day 27 / 52 · October — Calculus & Optimization (Day 27-34)

Concept

The derivative is the coefficient of the linear function that best approximates a function near a point, so its value tells you how many times the output changes for a small change in the input. For a multivariable function, the gradient collects the partial derivatives with respect to each variable into a vector; it points in the direction of steepest increase at that point, and its magnitude is that rate of increase. The chain rule states that the derivative of a composite function is the product of the derivatives at each stage, and in the multivariable case this generalizes to a product of Jacobian matrices. Backpropagation computes this Jacobian product from the output side toward the input side, reusing intermediate results so that gradients can be obtained far more cheaply when there are many parameters. Gradient descent repeatedly moves a small step in the direction opposite the gradient to find a local minimum; the practical crux is that too large a step size (learning rate) causes divergence, while too small a one makes convergence painfully slow.

Optimization, curve fitting, and parameter tuning all run on gradients, and derivatives are exactly the language you need whenever you have to reason about a function's sensitivity — as with market-maker pricing curves. Without the chain rule you cannot compute the sensitivity of a composed system.

Code & Formula

# Day 27 — 미분·기울기·연쇄법칙
# 수치미분으로 도함수를 근사하고, 연쇄법칙 f(g(x))의 도함수를 직접 계산과 비교한다.

def numerical_diff(f, x, h=1e-6):
    return (f(x + h) - f(x - h)) / (2 * h)


def f(x):
    return x ** 3 + 2 * x


def f_prime_exact(x):
    return 3 * x ** 2 + 2


x0 = 2.0
print(f"f'({x0}) 수치미분 근사 = {numerical_diff(f, x0):.6f}")
print(f"f'({x0}) 해석적 값   = {f_prime_exact(x0):.6f}")

# 연쇄법칙: h(x) = g(f(x)), g(u) = sin(u) 라 하면 h'(x) = g'(f(x)) * f'(x)
import math


def g(u):
    return math.sin(u)


def h(x):
    return g(f(x))


def h_prime_chain_rule(x):
    g_prime = math.cos(f(x))  # g'(u) = cos(u), u = f(x)
    return g_prime * f_prime_exact(x)


print(f"\nh'({x0}) 수치미분 근사 = {numerical_diff(h, x0):.6f}")
print(f"h'({x0}) 연쇄법칙 계산 = {h_prime_chain_rule(x0):.6f}")

Exercise

Pick a simple multivariable function, compute its gradient by hand, compare it against a numerical derivative, then run a few steps of gradient descent yourself and observe the learning-rate threshold where convergence turns into divergence.

Practical Connection

An LMSR market maker's price is defined as the partial derivative of the cost function, so derivatives and gradients feed directly into understanding Verex's price calculation and its sensitivity to slippage.

If you study this on a given day, add a note link and a ✅ to this line in the source curriculum (docs/knowledge/math-50-curriculum.md) and this spot will lead straight to the note body. You can also write directly on this page — but regenerating overwrites it, so it's safer to keep anything you want to save as markdown under docs/algorithms/.


한국어

미분·기울기·연쇄법칙 TODO

Math · Day 27 / 52 · 10월 — 미적분·최적화 (Day 27–34)

개념

미분은 한 점 근방에서 함수를 가장 잘 근사하는 선형 함수의 계수이며, 그래서 미분값은 '입력이 조금 변할 때 출력이 몇 배로 변하는가'를 뜻한다. 다변수 함수에서는 각 변수에 대한 편미분을 모은 벡터가 기울기(gradient)이고, 이 벡터는 그 점에서 함수값이 가장 빠르게 증가하는 방향을 가리키며 크기는 그 증가율이다. 연쇄법칙은 합성함수의 미분이 각 단계 미분의 곱이라는 규칙이고, 다변수에서는 야코비 행렬의 곱으로 일반화된다. 역전파는 이 야코비 곱을 출력 쪽에서 입력 쪽으로 계산해 중간 결과를 재사용함으로써, 파라미터가 많을 때 기울기를 훨씬 싸게 얻는 방법이다. 경사하강은 기울기의 반대 방향으로 조금씩 이동해 극소점을 찾는 절차이고, 이동 폭(학습률)이 너무 크면 발산하고 너무 작으면 수렴이 느리다는 점이 실용적 핵심이다.

최적화, 곡선 적합, 파라미터 튜닝은 모두 기울기 위에서 돌아가고, 마켓메이커 곡선처럼 함수의 민감도를 따져야 하는 문제에서도 미분이 그대로 언어가 된다. 연쇄법칙을 모르면 합성된 시스템의 민감도를 계산할 수 없다.

코드 · 수식

# Day 27 — 미분·기울기·연쇄법칙
# 수치미분으로 도함수를 근사하고, 연쇄법칙 f(g(x))의 도함수를 직접 계산과 비교한다.

def numerical_diff(f, x, h=1e-6):
    return (f(x + h) - f(x - h)) / (2 * h)


def f(x):
    return x ** 3 + 2 * x


def f_prime_exact(x):
    return 3 * x ** 2 + 2


x0 = 2.0
print(f"f'({x0}) 수치미분 근사 = {numerical_diff(f, x0):.6f}")
print(f"f'({x0}) 해석적 값   = {f_prime_exact(x0):.6f}")

# 연쇄법칙: h(x) = g(f(x)), g(u) = sin(u) 라 하면 h'(x) = g'(f(x)) * f'(x)
import math


def g(u):
    return math.sin(u)


def h(x):
    return g(f(x))


def h_prime_chain_rule(x):
    g_prime = math.cos(f(x))  # g'(u) = cos(u), u = f(x)
    return g_prime * f_prime_exact(x)


print(f"\nh'({x0}) 수치미분 근사 = {numerical_diff(h, x0):.6f}")
print(f"h'({x0}) 연쇄법칙 계산 = {h_prime_chain_rule(x0):.6f}")

연습

간단한 다변수 함수 하나를 골라 기울기를 손으로 구한 뒤, 수치 미분과 값을 비교하고 경사하강을 몇 스텝 직접 돌려 학습률에 따라 수렴·발산이 갈리는 지점을 관찰하라.

실무 · Verex 연결

LMSR 마켓메이커의 가격은 비용 함수의 편미분으로 정의되므로, 미분과 기울기는 Verex의 가격 계산과 슬리피지 민감도를 이해하는 데 직접 쓰인다.

공부한 날 원본 커리큘럼(docs/knowledge/math-50-curriculum.md)의 이 줄에 노트 링크와 ✅ 를 붙이면, 이 자리는 노트 본문으로 바로 이어집니다. 노트 없이 이 페이지에 바로 적어도 됩니다 — 다만 다시 생성하면 덮어쓰이므로, 남길 글은 docs/algorithms/ 의 마크다운으로 쓰는 편이 안전합니다.

← 26. 최소제곱법(Least Squares)28. 편미분/그래디언트 →