Monte Carlo 方法

Monte Carlo 積分

import random, math

def mc_integral(f, a, b, n=100000):
    total = 0
    for _ in range(n):
        x = random.uniform(a, b)
        total += f(x)
    return (b - a) * total / n

# 計算 ∫₀¹ x² dx = 1/3
f = lambda x: x*x
result = mc_integral(f, 0, 1)
print(f"Monte Carlo: {result:.6f} (理論值: {1/3:.6f})")

# 計算複雜區域面積
import matplotlib.pyplot as plt

def mc_area(n=100000):
    inside = 0
    for _ in range(n):
        x, y = random.random()*2-1, random.random()*2-1
        if x**3 + y**4 < 1:
            inside += 1
    return 4 * inside / n

area = mc_area()
print(f"x³ + y⁴ < 1 的面積: {area:.4f}")

Vibe Prompt

「用 Monte Carlo 計算複雜函數的積分,並畫出收斂過程(誤差隨樣本數的變化)。」

解鎖完整教學內容

本章為付費內容。加入專案即可解鎖超過 5000 字的深度解析,包含 10 個以上神級 Prompt 與真實 Source Code 範例!