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.

Where it lands in Jayverse

Key expressions

Words and phrases from this page worth keeping, with the Korean meaning and the sentence they come from.

Expression뜻 · 쓰이는 자리
tangent line접선 · 뉴턴법에서 현재 점에서 그은 직선을 말할 때. "drawing the tangent line at the current point"
quadratic convergence이차 수렴(오차가 제곱으로 줄어듦) · 근처에서 매우 빠르게 수렴하는 성질. "the error shrinks quadratically each step"
contraction mapping축소 사상 · 반복할수록 값들이 서로 가까워지는 함수를 말할 때. "if g is a contraction mapping it converges"
diverge or oscillate발산하거나 진동하다 · 반복 계산이 수렴하지 않고 불안정할 때. "can diverge or oscillate with a bad initial guess"
range safeguards범위 안전장치 · 값이 허용 범위를 벗어나지 않도록 막는 장치. "needs an iteration cap and range safeguards"
closed-form solution닫힌 형태의 해(공식으로 바로 구해지는 해) · 반복 계산 없이 수식으로 바로 풀리는 해가 없을 때. "Invariants with no closed-form solution"
point of failure실패 지점, 취약점 · 시스템에서 문제가 생길 수 있는 지점을 말할 때. "a potential point of failure"
LMSR로그마켓점수규칙(Logarithmic Market Scoring Rule) · 예측시장 가격을 자동으로 매기는 방식, Verex의 확률 계산에도 쓰임. "numerical solvers related to LMSR all use the same tool"
StableSwap커브(Curve)식 스테이블코인 AMM 불변식 · 폐형해가 없어 뉴턴법 등으로 반복적으로 풀어야 하는 유동성 곡선. "Newton's Method and Fixed-Point Iteration (Essential for StableSwap)"

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 관련 수치 해법 모두 같은 도구를 쓰며, 반복 횟수 상한과 반올림 방향이 곧 보안 속성이 된다.

Jayverse에서의 위치

핵심 표현

이 페이지의 영어 본문에서 배울 만한 단어와 표현, 뜻과 나온 자리.

Expression뜻 · 쓰이는 자리
tangent line접선 · 뉴턴법에서 현재 점에서 그은 직선을 말할 때. "drawing the tangent line at the current point"
quadratic convergence이차 수렴(오차가 제곱으로 줄어듦) · 근처에서 매우 빠르게 수렴하는 성질. "the error shrinks quadratically each step"
contraction mapping축소 사상 · 반복할수록 값들이 서로 가까워지는 함수를 말할 때. "if g is a contraction mapping it converges"
diverge or oscillate발산하거나 진동하다 · 반복 계산이 수렴하지 않고 불안정할 때. "can diverge or oscillate with a bad initial guess"
range safeguards범위 안전장치 · 값이 허용 범위를 벗어나지 않도록 막는 장치. "needs an iteration cap and range safeguards"
closed-form solution닫힌 형태의 해(공식으로 바로 구해지는 해) · 반복 계산 없이 수식으로 바로 풀리는 해가 없을 때. "Invariants with no closed-form solution"
point of failure실패 지점, 취약점 · 시스템에서 문제가 생길 수 있는 지점을 말할 때. "a potential point of failure"
LMSR로그마켓점수규칙(Logarithmic Market Scoring Rule) · 예측시장 가격을 자동으로 매기는 방식, Verex의 확률 계산에도 쓰임. "numerical solvers related to LMSR all use the same tool"
StableSwap커브(Curve)식 스테이블코인 AMM 불변식 · 폐형해가 없어 뉴턴법 등으로 반복적으로 풀어야 하는 유동성 곡선. "Newton's Method and Fixed-Point Iteration (Essential for StableSwap)"

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

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