Exclude range within random range between negative and positive float. c# csharp

Have a variable that I give a random range between -2.0f and 2.0f, but I don’t want it to pick a number between -0.6f and 0.6f.

How do I got about doing this?

You have two possible ranges (-2 to -0.6, 0.6 to 2), so compare their size (equal in this example), do a weighted selection between them, and then select within the chosen range.

2 Likes

The easiest (and not very efficient) way of doing it is to have one loop that continues to generate random floats until it is in the desired ranges, here’s an example I made:

I created getRandomFloat using the same parameter structure as ranges (-2 to -0.6, 0.6 to 2)

System.Random rand = new System.Random(); //Note using System.Random here and not Unity.Random

    //Returning a random float between rMin1 and rMax2, but excluding numbers between rMax1 and rMin2)
    float getRandomFloat(float rMin1,float rMax1, float rMin2, float rMax2)
    {
        //Make sure ranges are valid
        bool validRanges = (rMin1 < rMax1) &&
                          (rMax1 < rMin2) &&
                          (rMin2 < rMax2);
        if (!validRanges)
            return(-666.0f); //Some kind of message saying that the ranges are wrong
       
        float newRand;

        do
        {
            //Returns float between 0.0f and 1.0f
            newRand = (float)rand.NextDouble();

            //Convert number to be in the range between rMin1 and rMax2
            newRand = (newRand * Mathf.Abs( rMax2 - rMin1 )) + rMin1;

            Debug.Log("try: " + newRand);
            //If the number is in the excluded range, then try again
        }while(newRand >= rMax1 && newRand <= rMin2);

        return newRand;
    }

This code has the potential for erroneous input and infinite loops, but the basic idea is there. I’m sure there is a more complicated algorithm that can do this more efficiently, but this is the straightforward solution for now. When I tested it myself it usually tries about 1-6 numbers (noticed by the debug.log i used) until it was in the right range and returned a good float.

I’ve tested this a bit with no errors but it’s late, if you run into further errors reply and I’ll see if I can help.

If it’s just this specific case you’re interested in, it’s pretty easy:

float value = Random.Range(0.6f, 2.0f); // value between 0.6 and 2.0
float sign = Random.value < 0.5f ? -1f : 1f; // select a negative or positive value

return sign * value;
3 Likes

This is a pretty good way.

Another way is to create a mapping function. One that converts a float between zero and one*. Then you simply pass in a random float and get back your value.

Animation curves are pretty good at storing arbitrary mapping functions.

*Random factoid: In my home industry this process is called coding data. It’s probably just going to confuse things to use the term here.