Files
2nd/10_Wiki/Topic_Programming/Frontend/몬테카를로 시뮬레이션(Monte Carlo Simulation).md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를
Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류.

- 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로
  자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거,
  동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거.
- 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming,
  Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business,
  Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로,
  나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는
  title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백).
  원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지.
- 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서.
- 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는
  지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지.
- Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경.
- 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
2026-07-05 00:33:48 +09:00

196 lines
6.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
id: wiki-2026-0508-몬테카를로-시뮬레이션-monte-carlo-simulati
title: 몬테카를로 시뮬레이션(Monte Carlo Simulation)
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Monte Carlo, MC Simulation, 몬테카를로법, Random Sampling]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [simulation, statistics, numerical-methods, probability]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: python
framework: numpy
---
# 몬테카를로 시뮬레이션(Monte Carlo Simulation)
## 매 한 줄
> **"매 random sampling 의 deterministic answer 추정"**. Stanislaw Ulam (Manhattan Project, 1946)이 neutron diffusion 위해 고안. 매 closed-form solution 없는 high-dim integral, optimization, risk modeling 의 해법 — 매 large-N law of large numbers 의 convergence.
## 매 핵심
### 매 4단계
1. **Define domain** of possible inputs (probability distribution).
2. **Sample randomly** from domain (PRNG).
3. **Compute deterministically** for each sample.
4. **Aggregate** results (mean, variance, percentiles).
### 매 수학 기반
- **Law of Large Numbers**: sample mean → expected value as N → ∞.
- **Convergence rate**: O(1/√N) — 매 4× samples 의 2× accuracy.
- **Curse of dimensionality 의 escape**: deterministic methods (grid) 매 d²/d³, MC 매 dimension-independent.
### 매 응용
1. **금융**: VaR, option pricing (Black-Scholes 외 path-dependent).
2. **물리**: particle transport, lattice QCD.
3. **AI**: Monte Carlo Tree Search (AlphaGo, MuZero).
4. **Engineering**: reliability analysis, sensitivity.
5. **3D rendering**: path tracing (Blender Cycles, Pixar RenderMan).
## 💻 패턴
### 1. π 추정 (canonical example)
```python
import numpy as np
def estimate_pi(n: int = 1_000_000) -> float:
pts = np.random.uniform(-1, 1, (n, 2))
inside = np.sum(pts[:, 0]**2 + pts[:, 1]**2 <= 1)
return 4 * inside / n
print(estimate_pi(10_000_000)) # ~3.14159
```
### 2. Option pricing (Black-Scholes via MC)
```python
import numpy as np
def european_call_mc(S0=100, K=105, r=0.05, sigma=0.2, T=1.0, n_paths=1_000_000):
Z = np.random.standard_normal(n_paths)
ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)
payoff = np.maximum(ST - K, 0)
return np.exp(-r * T) * payoff.mean()
price = european_call_mc()
print(f"Call price: {price:.4f}")
```
### 3. Value at Risk (VaR)
```python
import numpy as np
def historical_var(returns: np.ndarray, alpha: float = 0.05) -> float:
return np.quantile(returns, alpha)
def parametric_var(mu, sigma, alpha=0.05, n=100_000):
samples = np.random.normal(mu, sigma, n)
return np.quantile(samples, alpha)
# portfolio daily returns
returns = np.random.normal(0.001, 0.02, 10_000)
print(f"5% VaR: {historical_var(returns):.4f}")
```
### 4. Monte Carlo integration
```python
import numpy as np
def mc_integrate(f, a, b, n=1_000_000):
x = np.random.uniform(a, b, n)
return (b - a) * np.mean(f(x))
# integrate sin(x) on [0, π] (true value = 2)
result = mc_integrate(np.sin, 0, np.pi)
print(result) # ~2.0
```
### 5. MCTS (Monte Carlo Tree Search) — AI
```python
import math, random
class Node:
def __init__(self, state, parent=None):
self.state = state
self.parent = parent
self.children = []
self.visits = 0
self.wins = 0
def ucb1(self, c=1.41):
if self.visits == 0:
return float('inf')
return self.wins / self.visits + c * math.sqrt(math.log(self.parent.visits) / self.visits)
def mcts(root, n_iter=10_000, get_actions=None, simulate=None):
for _ in range(n_iter):
# 1. select via UCB1
node = root
while node.children:
node = max(node.children, key=lambda n: n.ucb1())
# 2. expand
for action in get_actions(node.state):
node.children.append(Node(apply(node.state, action), node))
# 3. simulate (random rollout)
leaf = random.choice(node.children) if node.children else node
result = simulate(leaf.state)
# 4. backpropagate
cur = leaf
while cur:
cur.visits += 1
cur.wins += result
cur = cur.parent
return max(root.children, key=lambda n: n.visits)
```
### 6. Variance reduction: antithetic variates
```python
import numpy as np
def mc_call_antithetic(S0=100, K=105, r=0.05, sigma=0.2, T=1.0, n=500_000):
Z = np.random.standard_normal(n)
ST_plus = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * Z)
ST_minus = S0 * np.exp((r - 0.5 * sigma**2) * T - sigma * np.sqrt(T) * Z)
payoff = (np.maximum(ST_plus - K, 0) + np.maximum(ST_minus - K, 0)) / 2
return np.exp(-r * T) * payoff.mean()
# 매 same N 의 ~2× variance reduction
```
### 7. Reproducibility (seed)
```python
import numpy as np
rng = np.random.default_rng(seed=42)
samples = rng.normal(0, 1, 1000) # reproducible
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Low-dim (d ≤ 3), smooth integrand | quadrature (Gauss, Simpson) — faster. |
| High-dim integral | MC — escapes curse of dimensionality. |
| Path-dependent option | MC. |
| European option (closed form) | Black-Scholes formula — instant. |
| Need confidence interval | MC + bootstrap. |
| Game tree search | MCTS + UCB1. |
**기본값**: NumPy MC 매 baseline, antithetic variates / control variates 매 variance reduction. JAX/CUDA 매 GPU acceleration.
## 🔗 Graph
- Adjacent: [[Bayesian_Inference|Bayesian Inference]]
## 🤖 LLM 활용
**언제**: high-dim integral, risk metrics, option pricing, game AI, sensitivity analysis.
**언제 X**: 매 closed-form 존재 매 (Black-Scholes European), low-dim quadrature 효율적인 case, deterministic answer 필요 매 (use seed).
## ❌ 안티패턴
- **Too few samples**: O(1/√N) 매 slow — 매 1% accuracy 의 N=10000+.
- **No seed in production**: non-reproducible bugs.
- **Bad PRNG**: `random.random()` 매 OK, `Math.random()` (JS) 매 not crypto-safe — but fine 매 simulation.
- **No variance reduction**: antithetic / control variates 매 free 2-10× speedup.
- **MC 의 deterministic 문제**: 매 closed form 존재 의 use that.
## 🧪 검증 / 중복
- Verified (Metropolis & Ulam 1949 original, Glasserman "Monte Carlo Methods in Financial Engineering" 2003, Kalos & Whitlock 2008).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — full content with π/option/VaR/MCTS patterns |