[英]C# How to Generate Random Number Depends on Probabilities
我遇到一種情況,我必須生成一個隨機數,該數字必須zero
或one
因此,代碼是這樣的:
randomNumber = new Random().Next(0,1)
但是,業務需求指出生成的數字為零的概率只有10%,生成的數字為1的概率只有90%
但是,我可以在生成隨機數時包括這種可能性嗎?
但是我不知道這種方式是否正確,此外,我認為C#應該已經准備好了一些東西
以10%的概率實現:
bool result = new Random().Next(1, 11) % 10 == 0;
以40%的概率實現:
bool result = new Random().Next(1, 11) > 6;
您可以這樣實現:
// Do not re-create Random! Create it once only
// The simplest implementation - not thread-save
private static Random s_Generator = new Random();
...
// you can easiliy update the margin if you want, say, 91.234%
const double margin = 90.0 / 100.0;
int result = s_Generator.NextDouble() <= margin ? 1 : 0;
首先,您應該保存對隨機實例的引用,以便獲得正確的隨機數字序列:
Random randGen = new Random();
要知道的第二件事是,隨機數的最大值是互斥的,因此要正確解決該問題,您應該執行以下操作:
int eitherOneOrZero = randGen.Next(1, 11) % 10;
要將其歸納為各種可能性的變化,可以執行以下操作:
Random randGen = new Random();
var trueChance = 60;
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
測試:
Random randGen = new Random();
var trueChance = 60;
var totalCount = 1000;
var trueCount = 0;
var falseCount = 0;
for (int i = 0; i < totalCount; i++)
{
int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
if (x == 1)
{
trueCount++;
}
else
{
falseCount++;
}
}
輸出:
正確:60.30%
假:39.70%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.