嗨,我注意到 Apache Maths 库(2.2 版)中有一些奇怪的行为,特别是在org.apache.commons.math.distribution.GammaDistributionImpl
课堂上,尽管我认为这可能也适用于其他发行版。
我想从不同的伽马分布中抽取样本,如下所示:
public static final double[] gammaSamples(final double[] shapeParameters)
{
double[] samples = new double[shapeParameters.length];
for (int i = 0; i < shapeParameters.length; i++)
{
GammaDistributionImpl gd = new GammaDistributionImpl(shapeParameters[i], 1.0d);
try
{
samples[i] = gd.sample();
}
catch (MathException e)
{
e.printStackTrace();
}
}
return samples;
}
但是,在运行代码时,我发现样本都可疑地相似,即给出
public static void main(String[] args)
{
System.out.println(Arrays.toString(gammaSamples(new double[] { 2.0d, 2.0d, 2.0d})));
}
一些示例输出是:
[0.8732612631078758, 0.860967116242789, 0.8676088095186796]
[0.6099133517568643, 0.5960661621756747, 0.5960661621756747]
[2.1266766239021364, 2.209383544840242, 2.209383544840242]
[0.4292184700011395, 0.42083613304362544, 0.42083613304362544]
我认为问题是由于默认随机数生成器对每个分布使用相同/相似的种子,我对此进行了如下测试:
public static final double[] gammaSamples(final double[] shapeParameters, final Random random)
{
double[] samples = new double[shapeParameters.length];
for (int i = 0; i < shapeParameters.length; i++)
{
GammaDistributionImpl gd = new GammaDistributionImpl(shapeParameters[i], 1.0d);
gd.reseedRandomGenerator(random.nextLong());
try
{
samples[i] = gd.sample();
}
catch (MathException e)
{
e.printStackTrace();
}
}
return samples;
}
这似乎解决了问题,即给出
public static void main(String[] args)
{
System.out.println(Arrays.toString(gammaSamples(new double[] { 2.0d, 2.0d, 2.0d }, new Random())));
}
一些示例输出是:
[2.7506981228470084, 0.49600951917542335, 6.841476090550152]
[1.7571444623500108, 1.941865982739116, 0.2611420777612158]
[6.043421570871683, 0.8852269293415297, 0.6921033738466775]
[1.3859078943455487, 0.8515111736461752, 3.690127105402944]
我的问题是:
这是怎么回事?这是一个错误还是它旨在让 Apache Maths 发行版以这种方式运行?
对我来说很奇怪,如果我创建单独的分发对象,我必须担心给他们的是什么种子,并确保它们足够不同。
另一个轻微的烦恼是我似乎无法将这些分布传递给我自己的 Random 对象,而是它们只允许通过 reseedRandomGenerator(long seed) 方法更改种子。在尝试重现结果时,能够将我自己的 Random 对象传递给它们将非常有用。
谢谢你的帮助。