Files
2nd/10_Wiki/Topics/Frontend/몬테카를로 시뮬레이션(Monte Carlo Simulation).md
T
Antigravity Agent f8b21af4be Wiki cleanup: error-doc removal, dedup merge, link normalization
10_Wiki/Topics 대규모 정리:
- 오류 캡처/미완성 stub 문서 227개 제거
- 교차폴더 중복 43클러스터 병합 (63파일 → redirect)
- 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건
- 카테고리 MOC 6개 신규 생성
- Graph 섹션 미해결 related-keyword 링크 10,058건 제거

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:52:15 +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 |