Convert floating point with rounding down in java

I have a line in my code as below:

float rand = (float) Math.random();

Math.random () returns a double, which is equal to >=0.0and <1.0. Unfortunately, the above value can set randto 1.0fif double is too close to 1.0.

Is there a way to apply double to a float so that, in the absence of an exact equal value, it always rounds to the next float value, and not to the nearest float value?

I am not looking for advice on RNG, nor workarounds, for example, after if(rand == 1.0f) rand = 0.0f;. In my case, this solution is a satisfactory way to fix my problem, and it has already been implemented. I'm just curious to know the “right” solution to this kind of number conversion.

+4
source share
2 answers

If you only want to round when rand==1.0f, then I am @paxdiablo's second answer. However, it looks like you're fine, always rounding, and just want to always round. If yes:

float rand = Math.nextDown((float)Math.random());

from javadoc:

nextDown (float f) Returns a floating point value adjacent to f in the direction of negative infinity.

In response to your comment, this is a good point. To avoid this problem, you can simply wrap the statement on a call Math.abs()that will have no effect unless the result is nextDown()negative.

float rand = Math.abs(Math.nextDown((float)Math.random()));
+1
source

, , double, float.

, - , , , , , , , .

float, , , , . , double float 1.0f.

, float .

if , , :

float frandom() {
    float ret = 1.0f;
    while (ret == 1.0f)
        ret = (float) Math.random();
    return ret;
}

, :

float frandom() {
    float ret = (float) Math.random();
    if (ret == 1.0f)
        ret = 0.0f;
    return ret;
}

float rand = frandom();

, , Java ( ) Javascript "" , frandom() Math. , :

float rand = Math.frandom();

, , ( , Java, ).


, float 1, 0.99999994 ( 2-1 , 1), 0.0f frandom() .

, , IEEE754.

+1

All Articles