In online documentation it states currently that Random.Range(float a, float b) will return value in range [a, b), but in earlier versions of documentation it was [a, b], so i wonder if they’ve changed function behavior(which is crazy it would lead to impossible to debug miracle bugs) or it is a simple documentation mistake?
Even if it is a change, I can’t see it breaking any real code. And it looks like just a doc fix.
In theory [1.0,2.0] could generate 2.0 exactly, but no one would ever count on actually rolling a 2.00000. The odds are 1 out of 2^23(?). And losing that number changes the probability space by an infinitesimal amount.
And everyone “knows” all random funcs never rolls the top number. I suspect most people, myself included, just assumed the range was really the standard [) or maybe even (). The normal way to write code with random float ranges is to assume it will never be an end value, but allow that it could be.
I can verify that it seems they just messed up the documentation (once again^^). Here’s a test that proofs that the max value is inclusive:
IEnumerator Start()
{
float max = 2.0f;
while (!Input.GetKeyDown(KeyCode.Return))
{
for (int i = 0; i < 100000; i++)
{
float v = Random.Range(0f, max);
if (v == max)
Debug.Log("Match " + v.ToString("0.000000000"));
}
yield return null;
}
}
At about 75 fps (7.5 million values per sec.) I get a “Match” on average every 2 - 4 seconds.
So nothing has changed, just the docs. Feel free to file a bug report in Unity. There’s a category for documentation.
edit
btw. “RAND_MAX” in C++ isn’t a variable you set. It’s just a constant and it represents by definition “the maximum value returned by rand”. Most random generators produce values within the32 or 64 bit unsigned integer range. The way you apply a max value is by using the modulo on the returned number. The modulo automatically excludes this value:
0 % 3 == 0
1 % 3 == 1
2 % 3 == 2
3 % 3 == 0
4 % 3 == 1
5 % 3 == 2
6 % 3 == 0
It’s the same logic as with zero based indices. Since zero is a value as well the value you specify as max devines the count of possible values.
for mix max you usually use:
min + rand() % (max-min)