【问题标题】:Get a random float within range excluding sub-range在不包括子范围的范围内获取随机浮点数
【发布时间】:2014-09-17 12:48:53
【问题描述】:

如何获得一个范围内的随机浮点数,不包括子范围?到目前为止,我唯一的想法是创建两个范围并从这两个范围中随机选择。我必须使用unity3d引擎中的float Random.Range(float min, float max)方法,所以代码是:

float GetRandomNumber(float min, float max, float minExclusive, float maxExclusive)
{
    float outcome;
    if (Random.Range(0, 1) < 0.5f)
        outcome = Random.Range(min, minExclusive);
    else
        outcome = Random.Range(maxExclusive, max);
    return outcome;
}

我可以放心地假设min &lt; minExclusive &lt; maxExclusive &lt; max

我尝试用谷歌搜索,但我发现唯一类似的问题涉及整数,它们的行为有点不同(例如,你可以轻松地迭代它们):

有人有更好的主意吗?

【问题讨论】:

  • 发布的代码不起作用,因为一半的值来自第一个块,一半来自第二个块,即使范围在两个块之间分布不均匀。
  • 链接的答案有什么问题?我认为这两个都提供了足够的技巧来制定合适的解决方案。这个问题的每个答案基本上都是这些的副本
  • @BigM the only similar problems I've found concern integers and they behave a bit differently
  • Int 和 Float 在这种情况下使用时并没有什么不同。 rich.okelly 的答案基本上是在代码中执行的stackoverflow.com/questions/195956/… 接受的答案

标签: c# random


【解决方案1】:

实现此目的的一种方法是生成您的随机数,忽略范围,然后适当地移动该值。这应该确保在一组可接受的值上均匀分布(假设这是您想要的):

var excluded = maxExclusive - minExclusive;
var newMax = max - excluded;
var outcome = Random.Range(min, newMax);

return outcome > minExclusive ? outcome + excluded : outcome;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-01
    • 2013-12-20
    • 2012-08-06
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多