dimanche 27 octobre 2019

Problems generating random float with values inferior than 1

I need a function for generating floats with values inferior than 1, I have this code:

public float randFloat(float min, float max) {
    float randomNum = rand.nextFloat() * ((max - min) + 1) + min;
    return randomNum;
}

*I'm adding 1 because this function is based in randomInt() and in that function, I add 1 because nextInt is normally exclusive of the top value, so add 1 to make it inclusive.

I call that function with very small values, for example:

minRadius = sh * 0.0001f;
maxRadius = sh * 0.0005f;
radius = Util.getInstance().randFloat(minRadius, maxRadius);

In that case sh is 1080, so:

minRadius = 0.108f;
maxRadius = 0.54f;

Then, that function should return values between 0.108 and 0.54, but instead of that, sometimes is returning values higher than 0.54f, for example, 1.1f, 1.4f, etc...

What is wrong in the function?




Aucun commentaire:

Enregistrer un commentaire