Probability Check code?

public bool ProbabilityCheck(float val)
    {
        float a = Random.Range(0, 100f);
        if (a <= val)
            return true;
        return false;
    }

I wrote like this but I don’t like…

Because, if coming val is 0, it will return true when a == 0, but it should return false because 0 is 0. Never should happened.

If doing like [ if (a < val ) ], then when val is 100 and a is 100, it will return false, even if it should return true.

So then? Of course I can do like if(val == 0) return false;

But no other way?

I’m not 100% sure what the issue is, if you’re trying to check val against a just use ==, Random.Range is inclusive, meaning both the lower and upper are included in the random.

public bool ProbabilityCheck(float val)
    {
        if (val == 0)
            return false;
        float a = Random.Range(0, 100f);
        if (a <= val)
            return true;
        return false;
    }

So I did revise like above, but don’t like this code. No neat way?

I think we need more context about what you want this to do. The script is obviously doing what it is told, but saying that 0 should return false means nothing to someone not involved in your project.

As a small tip, you can simply usereturn (a <= val); if all you wanted to do is return the bool.

As far as excluding 0 from the comparisons, yes using val== 0 as a check and returning from there is probably the best way to go about it, as you killing the function right then and there, allowing the program to continue without executing the rest of the code which is redundant in that context, apparently.

Something like this?

public bool ProbabilityCheck(float val)
{
    return Random.value < val;
}

where val is betwen 0f (0% probablility) and 1f (100% probablility)

Just normal probability check. Like in-game’s critical hit occurance, item drop probability, etc. Most of them will shows like 15% or 0.02% (in case of super rare item drop)

So https://docs.unity3d.com/ScriptReference/Random-value.html
Random.value is 1.0 inclusive, if val is 1 and Random.value is 1, then both become same, then will return false.

So then the best is this?

public bool ProbabilityCheck(float val)
    {
        if (val == 0)
            return false;
        return (Random.Range(0, 100f) <= val);
    }

Ah, good to know… then maybe

public bool ProbabilityCheck(float val)
{
     return val > 0 && Random.value <= val;
}
2 Likes