【发布时间】: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 < minExclusive < maxExclusive < max。
我尝试用谷歌搜索,但我发现唯一类似的问题涉及整数,它们的行为有点不同(例如,你可以轻松地迭代它们):
- Generating random number excluding range
- How can I generate a random number within a range but exclude some?
有人有更好的主意吗?
【问题讨论】:
-
发布的代码不起作用,因为一半的值来自第一个块,一半来自第二个块,即使范围在两个块之间分布不均匀。
-
链接的答案有什么问题?我认为这两个都提供了足够的技巧来制定合适的解决方案。这个问题的每个答案基本上都是这些的副本
-
@BigM
the only similar problems I've found concern integers and they behave a bit differently -
Int 和 Float 在这种情况下使用时并没有什么不同。 rich.okelly 的答案基本上是在代码中执行的stackoverflow.com/questions/195956/… 接受的答案