1

I'm using unity's random.value function (I think i saw this behavior also somewhere else), which as the documentation states works as follows.

Both 0.0 and 1.0 may be returned by this property. This behaviour is different to that of many other random number generators which return a value less than but never exactly equal to 1.0.

Now when using this method somewhat like this

int[] array = {1, 2, 3, 4, 5};
int number = array[(int)(Random.value * array.length)];

do i have to worry about getting an ArrayOutOfRangeException, when all planets are lined up? And does that mean that i'm forced to do it like this for the sake of me beeing abled to sleep at night?

int number = array[(int)((Random.value - Float.epsilon) * array.length)];

Further i would like to know why someone would create a random function that isnt returning numbers only smaller than one? Is there any hidden benefit in doing it that way?

T. Grumser
  • 99
  • 3
  • 18

1 Answers1

3

No, you shouldn't use that. If it does return 1.0, you'll have problems. Frankly I think it was an API design mistake on Unity's part.

However, this is not how I would recommend that you write the code anyway. Instead, use the Random.Range method:

int number = array[Random.Range(0, array.Length)];

There, the overload accepting int values treats the maximum as exclusive rather than inclusive.


Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thanks, i did not know about the Random.Range method - Strange that unity made a mistake like that. – T. Grumser Dec 07 '18 at 10:16
  • @T.Grumser: I suspect it was an early mistake, and can't be fixed in case someone has a fixed-seed that they know *should* produce 1.0 :( – Jon Skeet Dec 07 '18 at 10:22