งูต้นฉบับปล่อยเหรียญผ่านชุดประตูก่อนรวมจำนวนความสำเร็จลงถาด

Python random.binomialvariate: จำลองจำนวนครั้งที่สำเร็จโดยไม่เขียนลูปเอง

พี่โชว์Engineering

ถ้าต้องจำลองว่า request จำนวน n ครั้งสำเร็จกี่ครั้ง เมื่อแต่ละครั้งมีโอกาส p เท่ากัน เราไม่ต้องเขียน sum(random() < p for ...) เองครับ random.binomialvariate(n, p) คืนจำนวนความสำเร็จจาก binomial distribution โดยตรง

WHY: ชื่อ distribution ทำให้สมมติฐานเห็นชัด

Binomial ใช้ได้เมื่อจำนวนครั้งคงที่ แต่ละครั้งมีสองผลลัพธ์ โอกาสสำเร็จคงที่ และการทดลองเป็นอิสระกัน เหมือนโยนเหรียญแบบเดิมหลายครั้ง หากโอกาสเปลี่ยนตามเวลา หรือผลครั้งก่อนกระทบครั้งถัดไป ฟังก์ชันนี้ยังรันได้แต่โมเดลผิด

import random
import unittest


def simulate_successes(rng, trials, probability):
    if trials < 0:
        raise ValueError("trials must be non-negative")
    if not 0.0 <= probability <= 1.0:
        raise ValueError("probability must be between zero and one")
    return rng.binomialvariate(trials, probability)


class BinomialTests(unittest.TestCase):
    def test_seed_reproduces_a_scenario(self):
        left = random.Random(20261005)
        right = random.Random(20261005)
        self.assertEqual(
            [simulate_successes(left, 20, 0.35) for _ in range(10)],
            [simulate_successes(right, 20, 0.35) for _ in range(10)],
        )

    def test_bounds_and_extremes(self):
        rng = random.Random(7)
        self.assertEqual(simulate_successes(rng, 12, 0.0), 0)
        self.assertEqual(simulate_successes(rng, 12, 1.0), 12)
        self.assertTrue(all(0 <= simulate_successes(rng, 12, 0.5) <= 12 for _ in range(100)))


if __name__ == "__main__":
    unittest.main()

Seed ช่วยให้ scenario ทดสอบทำซ้ำได้ แต่ไม่ควร assert ค่าสุ่มชุดยาวที่ผูกกับ implementation หาก contract ไม่รับประกันลำดับข้ามเวอร์ชัน ทดสอบ invariants, extremes และสถิติด้วย tolerance ที่สมเหตุผลแทน

โมดูล random เป็น pseudo-random generator สำหรับ simulation ไม่ใช่ token, OTP หรือ secret งานความปลอดภัยใช้ secrets และอย่านำผล binomial ไปแทนข้อมูลจริงโดยไม่ตรวจ calibration

Recap

  • ใช้เมื่อมี n ครั้ง, สองผลลัพธ์, p คงที่ และเป็นอิสระ
  • validate n กับ p ที่ boundary
  • seed เพื่อทำ scenario ซ้ำ ไม่ใช่สร้างความลับ
  • ทดสอบ bounds และ assumptions มากกว่าจำเลขสุ่มชุดเดียว