Vika
Vika

Reputation: 429

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

Upvotes: 1

Views: 933

Answers (5)

GoTouchGrass
GoTouchGrass

Reputation: 3

Well, just make if{} in Update() to pick another random number with same function if it is 0.0f. No way it will get 0.0f two times in a row

Upvotes: 0

bolov
bolov

Reputation: 75697

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.

Upvotes: 1

Geeky Quentin
Geeky Quentin

Reputation: 2508

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

Upvotes: 1

Milad Qasemi
Milad Qasemi

Reputation: 3049

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

Upvotes: 4

Voidsay
Voidsay

Reputation: 1550

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

Upvotes: 2

Related Questions