Home > Mobile >  Random number generator but avoid 0
Random number generator but avoid 0

Time:09-02

I am generating a random number between a range but I want the number to not be 0. It can be 0.1, 0.2...etc but not 0. How do I do this?

public float selectedValue;

void Start()
 {
    selectedValue = Random.Range(-0.5f, 0.5f);
 }

CodePudding user response:

Keep finding random values until its value is not zero

float RandomNumExceptZero (float min, float max){
  float randomNum = 0.0f;
    do {
        randomNum = Random.Range (min, max);
    } while (randomNum == 0.0f );
    return randomNum ;
}

CodePudding user response:

Building on the suggestion of @Psi you could do this:

public float selectedValue;
void Start()
{
    selectedValue = Random.Range(float.MinValue, 0.5f)*(Random.value > 0.5f?1:-1);
}

CodePudding user response:

Random.Range() takes in 2 arguments in which the second argument is exclusive. You can use it for your advantage by excluding the value 0. The logic used is to find a random value between -0.5f and 0 (exclusive). Use another randomizer to get either a positive value or a negative value

public float selectedValue;

void Start()
{
    selectedValue = Random.Range(-0.5f, 0);
    int sign = Random.Range(0, 2);

    // the value sign can be either 0 or 1
    // if the sign is positive, invert the sign of selectedValue
    if(sign) selectedValue = -selectedValue;
}

CodePudding user response:

I just want to point out that there are 2,113,929,216 (*) float values in the interval [-0.5, 0.5) which gives a ≈ 0.000000047305 % chance that exactly 0.0f will be generated.


(*) found by brute force with C std::next_after but both implementation should follow IEEE 754 so I don't expect to be language differences in this regard, unless Unity somehow doesn't use subnormal numbers.

  • Related