获得越来越大的随机数越来越不可能

Red*_*ter 2 java random

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

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

Mig*_*ork 5

我已经在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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

卡坦2(加两个骰子)

class Catan2 extends AbstractGenerator {

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

结果:

0 : *******************
1 : ******************
2 : ****************
3 : **************
4 : ************
5 : *********
6 : *******
7 : *****
8 : ***
9 : *
Run Code Online (Sandbox Code Playgroud)

卡坦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;
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

0 : ***********************
1 : *********************
2 : *******************
3 : ***************
4 : ***********
5 : *******
6 : *****
7 : ***
8 : *
9 : *
Run Code Online (Sandbox Code Playgroud)

卡坦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;
    }
}
Run Code Online (Sandbox Code Playgroud)

结果:

0 : ***************************
1 : ************************
2 : ********************
3 : **************
4 : *********
5 : *****
6 : ***
7 : *
8 : *
9 : *
Run Code Online (Sandbox Code Playgroud)

我认为“ Catan 3”是其中最好的。

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

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