作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何获得 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 个数字,这里它们显示为条形。
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 : *
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 : *
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/
使用这段代码: x = x + (canvas.height/250); 每 1 毫秒发生一次,应该按 Canvas 大小的比例向 x 添加一个量。然后绘制 x 因此 x 应该在不同的屏幕尺寸上以相同
我是一名优秀的程序员,十分优秀!