C++11 <random> Library ให้ Random Number Generation ที่ทันสมัย แทน rand() แบบเก่า โครงสร้างหลักคือ Engine (Bit Generator) + Distribution (Statistical Mapping)
องค์ประกอบหลัก
- Random Device (
std::random_device): Non-deterministic Seed Source (Hardware/OS Entropy) - Engine (
std::mt19937): Mersenne Twister 32-bit Pseudo-RNG (Fast, High Quality, Period 2^19937-1) - Distribution: แปลง Bits ให้เป็น Statistical Distribution ที่ต้องการ
ตัวอย่าง: Uniform Real Distribution
#include <random>
#include <iostream>
int main() {
// 1. Seed Engine ด้วย Random Device (ครั้งเดียว)
std::random_device rd;
std::mt19937 gen(rd()); // Mersenne Twister Engine
// 2. Define Distribution: Uniform Real [20.0, 22.0]
std::uniform_real_distribution<double> dist(20.0, 22.0);
// 3. Generate 20 Numbers
for (int i = 0; i < 20; ++i) {
std::cout << dist(gen) << '\n';
}
return 0;
}
ผลลัพธ์ตัวอย่าง
21.5311
21.7195
21.0961
21.9679
21.197
21.2989
20.6333
20.441
20.7124
20.2654
21.1877
20.4824
20.0575
20.9432
21.222
21.162
21.1029
20.2253
21.5669
20.3357
Distribution อื่นๆ ที่น่าสนใจ
| Distribution | Parameters | ใช้สำหรับ |
|---|---|---|
uniform_int_distribution<T> | min, max (Inclusive) | Integer สุ่มใน Range |
normal_distribution<T> | mean, stddev | Gaussian/Noise |
exponential_distribution<T> | lambda | Inter-arrival Times |
poisson_distribution<T> | mean | Count Events |
bernoulli_distribution | p (probability) | True/False (Coin Flip) |
gamma_distribution<T> | alpha, beta | Bayesian, Queuing |
Best Practices
- Seed ครั้งเดียว: สร้าง
genและdistนอก Loop - Thread Safety: ใช้
thread_localEngine ต่อ Thread - Reproducibility: Seed ด้วย Fixed Value สำหรับ Testing (
std::mt19937 gen(42);) - Performance: Distribution Object เบา Engine Object หนัก - Reuse ทั้งคู่
- Cryptography: อย่าใช้ mt19937 ใช้
std::random_deviceโดยตรง หรือ Crypto Libraries
Seed Sequences สำหรับ Entropy ดีกว่า
// ดีกว่า random_device() เดียว (ถ้า random_device เป็น Pseudo)
std::seed_seq seq{rd(), rd(), rd(), rd(), rd(), rd(), rd(), rd()};
std::mt19937 gen(seq);
สรุป
std::mt19937 + std::uniform_real_distribution (หรือ Int) เป็น Standard Pattern สำหรับ Random Generation ใน C++11+ ให้ Quality, Speed, และ Flexibility ที่ rand() ทำไม่ได้