【问题标题】:Random Even Logarithmic Distribution Between Two Doubles两个双精度数之间的随机偶数对数分布
【发布时间】:2015-01-20 09:21:19
【问题描述】:

也许我想太多了,但我正在尝试找到一种很好的方法来获得均匀对数分布的两点之间的随机数。 假设我有两个界限 0.001 和 1000,我想找到 6 个对数均匀分布的随机数。所以像这样的数字:0.002、0.033、0.543、1.634、34.673、765.234 ......现在说我正在寻找 7 个随机数,它们也会在这个范围内大致均匀排列......我正在使用爪哇

【问题讨论】:

  • 你能生成-3.0到3.0之间均匀分布的随机数吗?
  • 那不是很简单... (-3.0 + (3.0 + 3.0) * rand.nextDouble());我可能会离开,因为我不确定是否有负面影响,但对于 3.0 并说 1.0,它将是 (1.0 + (3.0 - 1.0) * rand.nextDouble());

标签: java algorithm random logarithm exponential


【解决方案1】:

这是你想要的吗?我将数字均匀分布在由极限对数形成的范围内,然后使用 Math.exp 转换回实际范围。我对结果数组进行了排序,因为您的示例显示了排序的数据。如果您不想这样做,请删除 Arrays.sort 调用。

为简单起见,我跳过了边界检查。大概是 0

检查限制是因为舍入误差至少在理论上可能导致结果刚好超出要求的范围。

import java.util.Arrays;
import java.util.Random;

public class Test {
  public static void main(String[] args) {
    Random rand = new Random(3);
    System.out.println(Arrays.toString(logRandom(rand, 0.001, 1000, 7)));
    System.out.println(Arrays.toString(logRandom(rand, 0.001, 1000, 7)));
    System.out.println(Arrays.toString(logRandom(rand, 0.001, 1000, 7)));
    System.out.println(Arrays.toString(logRandom(rand, 0.001, 1000, 7)));
  }

  public static double[] logRandom(Random rand, double lowerLimit,
      double upperLimit, int count) {
    double[] result = new double[count];
    double logLower = Math.log(lowerLimit);
    double logUpper = Math.log(upperLimit);
    for (int i = 0; i < count; i++) {
      double raw = rand.nextDouble();
      result[i] = Math.exp(raw * (logUpper - logLower) + logLower);
      if (result[i] < lowerLimit) {
        result[i] = lowerLimit;
      } else if (result[i] > upperLimit) {
        result[i] = upperLimit;
      }
    }
    Arrays.sort(result);
    return result;
  }

}

【讨论】:

  • 非常感谢...这正是我所需要的,你的救命稻草 :)
猜你喜欢
  • 1970-01-01
  • 2016-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-02
  • 2016-02-08
相关资源
最近更新 更多