เมธอด Random.NextDouble() ใน C# ใช้สร้างจำนวนทศนิยมสุ่ม (double) ที่มีค่ามากกว่าหรือเท่ากับ 0.0 และน้อยกว่า 1.0 (ช่วง [0.0, 1.0))
รูปแบบไวยากรณ์ (Syntax)
public virtual double NextDouble();
ตัวอย่างที่ 1: สุ่มทศนิยมพื้นฐาน
using System;
public class Demo
{
public static void Main()
{
Random r1 = new Random();
Random r2 = new Random();
Byte[] arr = new Byte[2];
r1.NextBytes(arr); // เติม byte array ด้วยค่าสุ่ม
Console.WriteLine("Random numbers in the byte array...");
for (int i = 0; i < 2; i++)
{
Console.WriteLine(arr[i]);
}
Console.WriteLine("\nRandom floating point numbers (NextDouble)...");
for (int i = 0; i < 5; i++)
{
Console.WriteLine(r2.NextDouble());
}
}
}
ผลลัพธ์ (ตัวอย่าง)
Random numbers in the byte array... 124 141 Random floating point numbers... 0.93591266727816 0.36406785872023 0.122396959514542 0.795166163144245 0.954394097884369
ตัวอย่างที่ 2: จำลองการกระจายตัว (Distribution Test)
using System;
public class Demo
{
public static void Main()
{
int[] val = new int[7]; // 0-6 buckets
Random r = new Random();
double d;
// สุ่ม 50 ครั้ง แล้วจัดกลุ่ม
for (int i = 0; i < 50; i++)
{
d = r.NextDouble();
// คูณ 5 แล้วปัดขึ้น (Ceiling) จะได้ index 1-5
val[(int)Math.Ceiling(d * 5)]++;
}
Console.WriteLine("Random Numbers Distribution (50 trials, 5 buckets)...");
for (int i = 0; i < 7; i++)
{
Console.WriteLine("Bucket " + i + ": " + val[i]);
}
}
}
ผลลัพธ์ (ตัวอย่าง)
Random Numbers Distribution (50 trials, 5 buckets)... Bucket 0: 0 Bucket 1: 13 Bucket 2: 9 Bucket 3: 12 Bucket 4: 8 Bucket 5: 8 Bucket 6: 0
การประยุกต์ใช้: สุ่มในช่วงที่กำหนด [min, max)
public double NextDouble(double min, double max)
{
Random r = new Random();
return min + (r.NextDouble() * (max - min));
}
// ใช้งาน
double randomPercent = NextDouble(0, 100); // 0.00 - 99.99...
double randomTemperature = NextDouble(-10.0, 40.0); // -10.0 ถึง 40.0
สรุป
- คืนค่า double ในช่วง [0.0, 1.0) เสมอ
- เหมาะสำหรับ: ความน่าจะเป็น, simulation, random percentage, interpolation
- สามารถขยายช่วงได้ด้วยสูตร:
min + (NextDouble() * (max - min)) - สำหรับความปลอดภัยทางเข้ารหัส ใช้
RandomNumberGeneratorแทน