整数範囲の開始と終了が与えられた場合、この範囲の間に正規分布のランダム整数を計算するにはどうすればよいですか?
正規分布が-+無限大になることを理解しています。テールをカットオフできると思うので、ランダムが範囲外で計算された場合は、再計算します。これにより、範囲内の整数の確率が高くなりますが、この効果が許容できる(<5%)限り、問題ありません。
public class Gaussian
{
private static bool uselast = true;
private static double next_gaussian = 0.0;
private static Random random = new Random();
public static double BoxMuller()
{
if (uselast)
{
uselast = false;
return next_gaussian;
}
else
{
double v1, v2, s;
do
{
v1 = 2.0 * random.NextDouble() - 1.0;
v2 = 2.0 * random.NextDouble() - 1.0;
s = v1 * v1 + v2 * v2;
} while (s >= 1.0 || s == 0);
s = System.Math.Sqrt((-2.0 * System.Math.Log(s)) / s);
next_gaussian = v2 * s;
uselast = true;
return v1 * s;
}
}
public static double BoxMuller(double mean, double standard_deviation)
{
return mean + BoxMuller() * standard_deviation;
}
public static int Next(int min, int max)
{
return (int)BoxMuller(min + (max - min) / 2.0, 1.0);
}
}
おそらく、範囲に対して標準偏差をある程度スケーリングする必要がありますが、その方法がわかりません。
答え:
// Will approximitely give a random gaussian integer between min and max so that min and max are at
// 3.5 deviations from the mean (half-way of min and max).
public static int Next(int min, int max)
{
double deviations = 3.5;
int r;
while ((r = (int)BoxMuller(min + (max - min) / 2.0, (max - min) / 2.0 / deviations)) > max || r < min)
{
}
return r;
}