简体   繁体   English

随机数生成器但避免 0

[英]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?我正在生成一个范围之间的随机数,但我希望该数字不为 0。它可以是 0.1、0.2...等但不是 0。我该怎么做?

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:基于@Psi 的建议,您可以这样做:

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 . Random.Range()接受 2 arguments ,其中第二个参数是独占的。 You can use it for your advantage by excluding the value 0 .您可以通过排除值0来利用它来获得优势。 The logic used is to find a random value between -0.5f and 0 (exclusive).使用的逻辑是在-0.5f0 (不包括)之间找到一个随机值。 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.我只想指出,在区间[-0.5, 0.5)中有2,113,929,216 (*) 个浮点值,这给出了≈ 0.000000047305 %的机会恰好生成0.0f


(*) 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. (*)通过 C++ std::next_after蛮力发现,但两种实现都应遵循 IEEE 754,所以我不希望在这方面存在语言差异,除非 Unity 以某种方式不使用次正规数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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