การสร้างตัวเลขสุ่มเทียม

การสุ่มตัวอย่างใน Python

James Chapman

Curriculum Manager, DataCamp

"สุ่ม" หมายความว่าอะไร?

{adjective} ทำ เกิดขึ้น หรือเลือกโดยไม่มีวิธีการหรือการตัดสินใจที่ชัดเจน

1 Oxford Languages
การสุ่มตัวอย่างใน Python

ตัวเลขสุ่มที่แท้จริง

  • สร้างจากกระบวนการทางกายภาพ เช่น การโยนเหรียญ
  • Hotbits ใช้การสลายตัวกัมมันตรังสี
  • RANDOM.ORG ใช้สัญญาณรบกวนในชั้นบรรยากาศ
  • ความสุ่มที่แท้จริงมีต้นทุนสูง
1 https://www.fourmilab.ch/hotbits 2 https://www.random.org
การสุ่มตัวอย่างใน Python

การสร้างตัวเลขสุ่มเทียม

  • การสร้างตัวเลขสุ่มเทียมนั้น ประหยัด และ รวดเร็ว
  • ตัวเลข "สุ่ม" ถัดไปคำนวณจากตัวเลข "สุ่ม" ก่อนหน้า
  • ตัวเลข "สุ่ม" แรกคำนวณจาก seed
  • seed ค่าเดียวกันให้ผลลัพธ์ตัวเลขสุ่มชุดเดิมเสมอ
การสุ่มตัวอย่างใน Python

ตัวอย่างการสร้างตัวเลขสุ่มเทียม

seed = 1
calc_next_random(seed)
3
calc_next_random(3)
2
calc_next_random(2)
6
การสุ่มตัวอย่างใน Python

ฟังก์ชันสร้างตัวเลขสุ่ม

  • นำหน้าด้วย numpy.random เช่น numpy.random.beta()
ฟังก์ชัน การแจกแจง ฟังก์ชัน การแจกแจง
.beta Beta .hypergeometric Hypergeometric
.binomial Binomial .lognormal Lognormal
.chisquare Chi-squared .negative_binomial Negative binomial
.exponential Exponential .normal Normal
.f F .poisson Poisson
.gamma Gamma .standard_t t
.geometric Geometric .uniform Uniform
การสุ่มตัวอย่างใน Python

การแสดงผลตัวเลขสุ่ม

randoms = np.random.beta(a=2, b=2, size=5000)
randoms
array([0.6208281 , 0.73216171, 0.44298403, ..., 
       0.13411873, 0.52198411, 0.72355098])
plt.hist(randoms, bins=np.arange(0, 1, 0.05))
plt.show()

hist-beta.png

การสุ่มตัวอย่างใน Python

Seed ของตัวเลขสุ่ม

np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
การสุ่มตัวอย่างใน Python

การใช้ seed ที่ต่างกัน

np.random.seed(20000229)
np.random.normal(loc=2, scale=1.5, size=2)
array([-0.59030264, 1.87821258])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.52619561, 4.9684949 ])
np.random.seed(20041004)
np.random.normal(loc=2, scale=1.5, size=2)
array([1.09364337, 4.55285159])
np.random.normal(loc=2, scale=1.5, size=2)
array([2.67038916, 2.36677492])
การสุ่มตัวอย่างใน Python

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

การสุ่มตัวอย่างใน Python

Preparing Video For Download...