gpt4 book ai didi

java - 获取随机数,数字越大越不可能

转载 作者:行者123 更新时间:2023-12-02 13:24:59 24 4
gpt4 key购买 nike

如何获得 k 到 h 范围内的随机数,使得数字越接近 h 就越不可能出现?

我需要一个 20 到 1980 之间的数字。

最佳答案

我在 Eclipse 中尝试了一些东西,这是结果。

interface Generator {       
double generate(double low, double high);
}


abstract class AbstractGenerator implements Generator {
protected final Random rand;

public AbstractGenerator()
{
rand = new Random();
}

public AbstractGenerator(long seed)
{
rand = new Random(seed);
}
}

现在各种生成器实现的结果:

我尝试生成 0 到 9 范围内的 100k 个数字,这里它们显示为条形。

Catan 2(添加两个骰子)

class Catan2 extends AbstractGenerator {

@Override
public double generate(double low, double high)
{
return low + (high - low) * Math.abs(-1 + (rand.nextDouble() + rand.nextDouble()));
}
}

结果:

0 : *******************
1 : ******************
2 : ****************
3 : **************
4 : ************
5 : *********
6 : *******
7 : *****
8 : ***
9 : *

Catan 3(添加三个骰子)

class Catan3 extends AbstractGenerator {

@Override
public double generate(double low, double high)
{
return low + (high - low) * Math.abs(-1.5 + (rand.nextDouble() + rand.nextDouble() + rand.nextDouble())) / 1.5;
}
}

结果:

0 : ***********************
1 : *********************
2 : *******************
3 : ***************
4 : ***********
5 : *******
6 : *****
7 : ***
8 : *
9 : *

Catan 4(添加四个骰子)

class Catan4 extends AbstractGenerator {

@Override
public double generate(double low, double high)
{
return low + (high - low) * Math.abs(-2 + (rand.nextDouble() + rand.nextDouble() + rand.nextDouble() + rand.nextDouble())) / 2D;
}
}

结果:

0 : ***************************
1 : ************************
2 : ********************
3 : **************
4 : *********
5 : *****
6 : ***
7 : *
8 : *
9 : *

我认为《卡坦 3》是其中最好的。

公式为:low+(high-low)*abs(-1.5+(RAND+RAND+RAND))/1.5

基本上,我得到一个“山”分布,然后将其居中并取其绝对值。然后我将其规范为所需的值。

关于java - 获取随机数,数字越大越不可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580242/

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