【问题标题】:Get a random number within a range with a bias获取一个有偏差的范围内的随机数
【发布时间】:2023-04-07 14:01:01
【问题描述】:

您好,我正在尝试一种方法来生成一个范围内的随机数 其中可能需要一个偏差,这将使数字更有可能根据偏差而更高/更低。

目前我正在使用这个

 public int randIntWeightedLow(int max, int min, int rolls){

    int rValue = 100;

    for (int i = 0; i < rolls ; i++) {
        int rand = randInt(min, max);

        if (rand < rValue ){
            rValue = rand;
        }
    }

    return rValue;
}

通过给我一个范围内的数字,这可以正常工作,我添加的卷越多,数字可能会越低。但是我遇到的问题是 3 卷和 4 卷之间存在很大差异。

我很想拥有类似的东西 公共无效randomIntWithBias(int min,int max,浮动偏差){ }

如果给出负偏差会使数字更频繁地变低,并且 正偏差会使数字更频繁地更高,但仍保持数字在最小值和最大值的随机范围内。

目前要生成我正在使用的随机数

 public int randInt(final int n1, final int n2) {
    if (n1 == n2) {
        return n1;
    }

    final int min = n1 > n2 ? n2 : n1;
    final int max = n1 > n2 ? n1 : n2;

    return rand.nextInt(max - min + 1) + min;
}

我是 java 和一般编码的新手,所以任何帮助都将不胜感激。

【问题讨论】:

  • 您可以使用nextGaussian() 乘以偏差来提供结果的偏差部分。
  • 是的,但是我会用它做什么......如果我只是将它添加到随机数中,那么如果最小值和最大值将被剔除..
  • 好的,请提供更多细节:准确定义结果如何受偏差参数影响,并提供一些示例。例如,偏差的大小是否会提高/降低(取决于符号)结果的下限/上限?

标签: java random


【解决方案1】:

好的,这是如何完成的快速草图。

首先,我建议使用Apache commons java library,它有整数采样 已经实现了不同的概率。我们需要Enumerated Integer Distribution

第二,使分布看起来呈线性的两个参数,p0 和 delta。 对于第 k 个值,相对概率为 p0 + k*delta。对于三角洲正 较大的数字将更有可能,因为 delta 负较小的数字将是 更有可能,delta=0 等于均匀采样。

代码(我的 Java 生锈了,请多多包涵)

import org.apache.commons.math3.distribution.EnumeratedIntegerDistribution;

public int randomIntWithBias(int min, int max, double p0, double delta){
    if (p0 < 0.0)
        throw new Exception("Negative initial probability");        
    int N = max - min + 1; // total number of items to sample

    double[] p = new double[N]; // probabilities
    int[] items = new int[N]; // items

    double sum = 0.0; // total probabilities summed
    for(int k = 0; k != N; ++k) { // fill arrays
        p[k] = p0 + k*delta;
        sum += p[k];
        items[k] = min + k;
    }

    if (delta < 0.0) { // when delta negative we could get negative probabilities
       if (p[N-1] < 0.0) // check only last probability
           throw new Exception("Negative probability");
    }

    for(int k = 0; k != N; ++k) { // Normalize probabilities
        p[k] /= sum;
    }

    EnumeratedIntegerDistribution rng = new EnumeratedIntegerDistribution(items, p);

    return rng.sample();
}

这就是这个想法的要点,代码可以(并且应该)优化和清理。

更新

当然,您可以使用二次函数来代替线性偏差函数。 一般二次函数具有三个参数 - 传递它们,以类似的方式填充概率数组,归一化,采样

【讨论】:

    猜你喜欢
    • 2017-01-01
    • 2023-02-06
    • 1970-01-01
    • 2020-07-18
    • 2010-10-01
    • 2015-04-23
    • 1970-01-01
    • 2015-06-02
    • 2021-07-24
    相关资源
    最近更新 更多