我想生成(1至6)之間的隨機數,有沒有什麼辦法改變歌廳數6比其他數字更多的機會呢?獲取特定的隨機數
例如用於該代碼
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,6);
label2.Text = m.ToString();
}
我想生成(1至6)之間的隨機數,有沒有什麼辦法改變歌廳數6比其他數字更多的機會呢?獲取特定的隨機數
例如用於該代碼
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,6);
label2.Text = m.ToString();
}
設p
是任何1..5
號的概率,1 - p
是6
概率:
//DONE: do not recreate Random
private static Random s_Generator = new Random();
private void pictureBox5_MouseClick(object sender, MouseEventArgs e) {
const double p = 0.1; // each 1..5 has 0.1 probability, 6 - 0.5
// we have ranges [0..p); [p..2p); [2p..3p); [3p..4p); [4p..5p); [5p..1)
// all numbers 1..5 are equal, but the last one (6)
int value = (int) (s_Generator.NexDouble()/p) + 1;
if (value > 6)
value = 6;
label2.Text = value.ToString();
}
取決於如何更容易。一個簡單的方法(但不是很靈活)將如下:
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,7);
if (m > 6) m = 6;
label2.Text = m.ToString();
}
那不會是隨機的然後。根據你想要什麼權,你可以改變的2它 - > 3,而不是獲得了33.33%的權重,因此
m = u.Next(1,2);
if(m == 2)
{
label2.Text = "6";
}
else
{
label2.Text = u.Next(1,5).ToString();
}
:如果你想體重,所以你會得到6一半的時候,你可以這樣做上。否則,正如評論者所說,你必須研究一個更具數學優雅的解決方案的概率分佈。
如果你想的1 ... 5,只需skwed 6完全隨機分佈的,那麼梅德的似乎最好。
如果您有什麼歪斜的所有號碼,那就試試這個:
你可以在得到的每一個號碼在數組中的百分比定義的可能性:
/*static if applicable*/
int[] p = { (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Ceiling((double)100/6) };
////The array of probabilities for 1 through p.Length
Random rnd = new Random();
////The random number generator
int nextPercentIndex = rnd.Next() % 100; //I can't remember if it's length or count for arrays off the top of my head
////Convert the random number into a number between 0 and 100
int TempPercent = 0;
////A temporary container for comparisons between the percents
int returnVal = 0;
////The final value
for(int i = 0; i!= p.Length; i++){
TempPercent += p[i];
////Add the new percent to the temporary percent counter
if(nextPercentIndex <= TempPercent){
returnVal = i + 1;
////And... Here is your value
break;
}
}
希望這有助於。
你應該看看[概率分佈(https://en.wikipedia.org/wiki/List_of_probability_distributions) – litelite
搜索條件:加權隨機 –