gpt4 book ai didi

java - Math.random() 如何用于数据分布?

转载 作者:行者123 更新时间:2023-11-29 08:36:32 24 4
gpt4 key购买 nike

我在代码中使用 Math.random() 将数据分发到单独的存储桶中。我想知道如果我在多个地方使用 Math.random(),它会使用不同的数字生成器还是相同的作为静态方法。

代码示例:

public void assignVariant1() {
int c1 = 0 , c2=0 , c3=0 ,c4=0;
for(int i = 0 ; i < 100000 ; i++)
{
if(Math.random() > 0.5)
{
c1++;
}else
{
c2++;
}

if(Math.random() > 0.5)
{
c3++;
}else
{
c4++;
}
}
System.out.println("c1 + c2 "+ (c1+c2));
System.out.println("c1 + c2 "+ (c3+c4));
}

在上面的代码中,它会为 Math.random() 调用使用相同的伪随机数生成器吗?

最佳答案

此处真正的答案是:阅读文档。

Math.random() 的 javadoc对此非常明确:

When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

new java.util.Random()

This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

所以要点是:如果您对库类有疑问,请阅读这些类附带的文档。在元层面上:努力自己“回答”这样的问题;向其他人寻求解释可能看起来像是绕道而行;但它实际上减慢你的速度。

关于java - Math.random() 如何用于数据分布?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43676378/

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