Workspace IndexMath › Day 31

Newton's Method and Fixed-Point Iteration (Essential for StableSwap) TODO

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

Concept

Newton's method finds a root of a function f by repeatedly drawing the tangent line at the current point and moving to that tangent line's root — the update subtracts f(x)/f'(x) from x each step. Near the root, if f' is nonzero and the initial guess is close enough, the error shrinks quadratically each step — quadratic convergence. Fixed-point iteration is a more general form that rewrites the equation as x = g(x) and iterates it; if g is a contraction mapping it converges, typically at a linear rate. Newton's method is fast but can diverge or oscillate with a bad initial guess or a small derivative, so it needs an iteration cap and range safeguards. When implementing it in integer arithmetic, the convergence tolerance should be set around an absolute error of 1 unit, and the direction of any remaining rounding error must be decided explicitly.

Invariants with no closed-form solution — like StableSwap's D or y — can only be solved iteratively, and on-chain every one of those iterations costs gas and is a potential point of failure.

Code & Formula

# Day 31 — 뉴턴법/고정점 반복(StableSwap 필수)
# f(x) = x^2 - 2 의 근(sqrt(2))을 뉴턴법으로 찾고, 오차가 제곱으로 줄어드는 이차수렴을 확인한다.

import math


def f(x):
    return x ** 2 - 2


def f_prime(x):
    return 2 * x


x = 1.0  # 초기값
true_root = math.sqrt(2)
print(f"뉴턴법으로 sqrt(2) = {true_root:.10f} 근사:\n")

prev_error = None
for step in range(6):
    error = abs(x - true_root)
    ratio = error / (prev_error ** 2) if prev_error else float("nan")
    print(f"step {step}: x = {x:.10f}, error = {error:.2e}, error/prev_error^2 = {ratio:.4f}")
    prev_error = error
    x = x - f(x) / f_prime(x)

print(f"\n최종 x = {x:.12f}")
print("오차/이전오차^2 값이 일정 상수로 수렴 -> 이차수렴(quadratic convergence)의 증거")

Exercise

Implement a function that solves for D in a StableSwap-style invariant using Newton's method with integer arithmetic, then check how many iterations it takes to converge under extremely imbalanced reserves, and whether any inputs cause it to diverge.

Practical Connection

Analyzing AMM invariants, inverting interest-rate models, and numerical solvers related to LMSR all use the same tool, and the iteration cap plus rounding direction become security properties in their own right.

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/.


한국어

뉴턴법/고정점 반복(StableSwap 필수) TODO

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

개념

뉴턴법은 함수 f의 근을 찾을 때 현재 점에서 접선을 그어 그 접선의 근으로 이동하는 반복법으로, x를 f(x)/f'(x)만큼 빼는 갱신을 반복한다. 근 근처에서 f'가 0이 아니고 초기값이 충분히 가까우면 오차가 매 단계 제곱으로 줄어드는 이차 수렴을 보인다. 고정점 반복은 방정식을 x = g(x) 꼴로 바꿔 반복하는 더 일반적인 형태이며, g가 축약사상이면 수렴하고 그 속도는 보통 일차이다. 뉴턴법은 빠르지만 초기값이 나쁘거나 도함수가 작으면 발산하거나 진동할 수 있어, 반복 횟수 상한과 구간 안전장치가 필요하다. 정수 산술로 구현할 때는 수렴 판정 기준을 절대 오차 1 단위 수준으로 두고, 남는 오차의 방향을 명시적으로 결정해야 한다.

닫힌 해가 없는 불변식(StableSwap의 D나 y 같은)은 반복법으로 풀 수밖에 없고, 온체인에서는 그 반복 하나하나가 가스이자 실패 가능 지점이다.

코드 · 수식

# Day 31 — 뉴턴법/고정점 반복(StableSwap 필수)
# f(x) = x^2 - 2 의 근(sqrt(2))을 뉴턴법으로 찾고, 오차가 제곱으로 줄어드는 이차수렴을 확인한다.

import math


def f(x):
    return x ** 2 - 2


def f_prime(x):
    return 2 * x


x = 1.0  # 초기값
true_root = math.sqrt(2)
print(f"뉴턴법으로 sqrt(2) = {true_root:.10f} 근사:\n")

prev_error = None
for step in range(6):
    error = abs(x - true_root)
    ratio = error / (prev_error ** 2) if prev_error else float("nan")
    print(f"step {step}: x = {x:.10f}, error = {error:.2e}, error/prev_error^2 = {ratio:.4f}")
    prev_error = error
    x = x - f(x) / f_prime(x)

print(f"\n최종 x = {x:.12f}")
print("오차/이전오차^2 값이 일정 상수로 수렴 -> 이차수렴(quadratic convergence)의 증거")

연습

StableSwap 형태의 불변식에서 D를 뉴턴법으로 푸는 함수를 정수 산술로 구현하고, 극단적 불균형 잔고에서 몇 번 만에 수렴하는지와 발산 사례가 있는지 확인해 보기.

실무 · Verex 연결

AMM 불변식 해석, 이자율 모델의 역함수 계산, LMSR 관련 수치 해법 모두 같은 도구를 쓰며, 반복 횟수 상한과 반올림 방향이 곧 보안 속성이 된다.

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

← 30. 라그랑주/KKT(개념)32. 고정소수점 산술(Q64.96) →