简体   繁体   中英

Random number generator but avoid 0

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM