- Home /
Is Random.Range() Really Maximally Inclusive?
According to the C# documentation, "Returns a random float number between and min [inclusive] and max [inclusive]." However, after running a few tests, it appears as though the max is actually exclusive. Something as simple as Debug.Log (Random.Range (1, 4);
never seems to return 4. Now is this some sort of error on my part, or is the documentation simply mistaken?
Try using Random.Range (0,1). $$anonymous$$aybe you are just unlucky :)
Answer by Psymon · Jul 30, 2013 at 12:19 PM
Only Range with float is maximally inclusive.
Range with integer is not maximally inclusive.
Of course! I can't believe I didn't notice that. Thank you!
Actually as of Unity 5, this is no longer the case. Both versions are documented as maximally exclusive. Haven't tested to verify but that's a subtle change that can cause some interesting statistical issues for existing code.
It's no longer the case. Tested and verified.
It still is the case and I'm on the latest Unity 5.3 build. If I write Random.Range(0, 2) only 0 or 1 get chosen
Answer by Seyyed · Jul 30, 2013 at 12:39 PM
You can use this: Random.Range (0.0, 1.0)
No point if he needs integers. He can just use range of 2.
Answer by EvalDaemon · Nov 12, 2016 at 07:58 AM
List<int> x = new List<int>();
x.Add(1);
x.add(100);
x.add(1000);
int i;
for(int i = 0; i < 100; i++)
{
i = Random.Range(0, (x.Count));
Debug.Log("i=" + i );
}
Always equals 0 to 2, never 3.
What was the point of this? Also your code is quite broken.
Answer by AmazinJacks · Apr 12, 2020 at 02:15 PM
EDIT: I was mistaken. Further down in the documentation page, it does clearly lay out that max for ints are exclusive, while max for floats are inclusive. I hadn't looked further.
I'm looking at https://docs.unity3d.com/ScriptReference/Random.Range.html which states quite specifically at the top of the Description:
Return a random float number between min [inclusive] and max [inclusive] (Read Only).
Note max is inclusive. Random.Range(0.0f, 1.0f) can return 1.0 as the value.
I'm using it for integers, which testing shows has an inclusive min and exclusive max. Perhaps it's different with floats, but the documentation confused me.
Your answer
Follow this Question
Related Questions
How can I do random choices 1 Answer
Generate a big digit with only 1 2 3 and 4,How to generate a big number that only countains 0 to 3 2 Answers
Multiple Cars not working 1 Answer
Non-repeating random number generator crashing unity 1 Answer
Need help with generating random Multiplier,Need help with generating random multipliers 0 Answers