gpt4 book ai didi

java - 在 Java 中生成遵循正态分布的数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:59:31 27 4
gpt4 key购买 nike

我想(随机地)生成数字,使数字遵循给定均值和方差的正态分布。我怎样才能做到这一点?

如果你能在 Java 的上下文中给出它会更好。人们可能会在这些答案中寻求帮助:但它们并不精确。 Generate random numbers following a normal distribution in C/C++

最佳答案

无耻地用谷歌搜索并摘自:http://www.javapractices.com/topic/TopicAction.do?Id=62

“魔法”发生在 Random.nextGaussian()

import java.util.Random;

/**
Generate pseudo-random floating point values, with an
approximately Gaussian (normal) distribution.

Many physical measurements have an approximately Gaussian
distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {

public static void main(String... aArgs){
RandomGaussian gaussian = new RandomGaussian();
double MEAN = 100.0f;
double VARIANCE = 5.0f;
for (int idx = 1; idx <= 10; ++idx){
log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
}
}

private Random fRandom = new Random();

private double getGaussian(double aMean, double aVariance){
return aMean + fRandom.nextGaussian() * aVariance;
}

private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}

关于java - 在 Java 中生成遵循正态分布的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389412/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com