กระบวนการ Monte Carlo

Monte Carlo Simulations ใน Python

Izzy Weber

Curriculum Manager, DataCamp

ขั้นตอนการจำลอง

  1. กำหนดตัวแปร input และเลือกการแจกแจงความน่าจะเป็น

  2. สุ่มค่า input จากการแจกแจงที่เลือก

  3. คำนวณผลลัพธ์จาก input ที่จำลองขึ้น

  4. สรุปผลลัพธ์

Monte Carlo Simulations ใน Python

การคำนวณค่า pi

สุ่มจุด $(x, y)$ โดย $x$ และ $y$ อยู่ในช่วง -1 ถึง 1

กราฟแสดงวงกลมภายในสี่เหลี่ยมพร้อมจุดที่สุ่มขึ้น

$$Area_{circle} = \pi $$

$$Area_{square} = 2 \times 2 = 4 $$

$$\frac{Area_{circle}}{Area_{square}} = \frac{\pi}{4} $$

$$\frac{n_{red}}{n_{all}} = \frac{\pi}{4} $$

$$ \pi = 4 \times \frac{n_{red}}{n_{all}}$$

Monte Carlo Simulations ใน Python

ขั้นตอนที่ 1

กำหนดตัวแปร input และเลือกการแจกแจงความน่าจะเป็น

  • Input: จุดแต่ละจุดแทนด้วยพิกัด $(x, y)$
  • การแจกแจงความน่าจะเป็น: $x$ และ $y$ มีการแจกแจงแบบสม่ำเสมอในช่วง -1 ถึง 1

 

circle_points = 0 
square_points = 0
Monte Carlo Simulations ใน Python

ขั้นตอนที่ 2

สุ่มค่า input จากการแจกแจงที่เลือก

 

สุ่มค่าพิกัด $x$ และ $y$ จากการแจกแจงแบบสม่ำเสมอในช่วง -1 ถึง 1:

for i in range(n):
    x = random.uniform(-1, 1)
    y = random.uniform(-1, 1)
Monte Carlo Simulations ใน Python

ขั้นตอนที่ 3

คำนวณผลลัพธ์จาก input ที่จำลองขึ้น

ตรวจสอบว่าแต่ละจุดอยู่ภายในวงกลมหรือไม่: ผลลัพธ์ขึ้นกับค่า $x$ และ $y$ ที่กำหนด

dist_from_origin = x**2 + y**2

ถ้าใช่ ให้เพิ่มจุดนั้นใน circle_points; และเพิ่มทุกจุดใน square_points เสมอ

if dist_from_origin <= 1:
     circle_points += 1
square_points += 1
Monte Carlo Simulations ใน Python

ขั้นตอนที่ 4

สรุปผลลัพธ์เพื่อตอบคำถามที่ต้องการ

 

หลังจากจำลองหลายรอบ คำนวณค่า pi!

pi = 4 * circle_points/ square_points
Monte Carlo Simulations ใน Python

รวมทุกขั้นตอน

n = 4000000
circle_points = 0 
square_points = 0

for i in range(n): x = random.uniform(-1, 1) y = random.uniform(-1, 1) dist_from_origin = x**2 + y**2 if dist_from_origin <= 1: circle_points += 1 square_point += 1
pi = 4 * circle_points / square_points print(pi)
3.142518
Monte Carlo Simulations ใน Python

มาฝึกกันเถอะ!

Monte Carlo Simulations ใน Python

Preparing Video For Download...