2

How can I get a random float within a range, excluding a sub-range? The only idea I have so far is to create two ranges and randomly choose from those two. I have to use float Random.Range(float min, float max) method found in unity3d engine, so the code would be:

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;
}

I can safely assume that min < minExclusive < maxExclusive < max.

I tried googling around but the only similar problems I've found concern integers and they behave a bit differently (e.g. you can easily iterate over them):

Does anyone have a better idea?

Community
  • 1
  • 1
Dunno
  • 3,632
  • 3
  • 28
  • 43
  • 2
    The posted code doesn't work since half the values would come from the first block and half from the second even if the range wasn't distributed evenly between the two blocks. – Sign Sep 17 '14 at 12:54
  • What's wrong with the linked Answers? I think both of these give enough tips to work out a fitting Solution. Every Answer to this Question will basically be a copy of these – BigM Sep 17 '14 at 13:01
  • possible duplicate of [How can I generate a random number within a range but exclude some?](http://stackoverflow.com/questions/6443176/how-can-i-generate-a-random-number-within-a-range-but-exclude-some) – BigM Sep 17 '14 at 13:04
  • @BigM `the only similar problems I've found concern integers and they behave a bit differently` – Rawling Sep 17 '14 at 13:09
  • Int and Float are not that different when used in such a scenario. rich.okelly's Answer is basically the accepted answer from http://stackoverflow.com/questions/195956/generating-random-number-excluding-range?lq=1 executed in code – BigM Sep 17 '14 at 13:22

1 Answers1

4

A way to achieve this would be to generate your random number ignoring the range and then shifting the value appropriately. This should ensure a uniform distribution over the set of acceptable values (assuming that this is what you want):

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

return outcome > minExclusive ? outcome + excluded : outcome;
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114