3

Possible Duplicate:
Random floating point double in Inclusive Range

I'm working on a project where I need the random float between 0.0 and 1.0 both inclusive. After considering a while I found out that it's propably not that important for my project anyway, so I just use the standard:

new Random().nextFloat();

which generates a float from 0.0 (inlcusive) to 1.0 (exclusive).

But I can't stop thinking how it's actually accomplished to make with 1.0 inclusive?

One method I could think of is (pseudocode):

new Random().nextFloat() * (1.0 + "lowest possible value above 0");

Another method I could think of is:

float myRandomFloat = 0;
float rand1 = new Random().nextFloat(); // [0;1)
float rand2 = 1.0f - new Random().nextFloat(); // (0;1]
boolean randPicker = new Random().nextBoolean();
if (randPicker)
    myRandomFloat = rand1;
else
    myRandomFloat = rand2;

But I think this ought to be more simple or not? So my real question is: Is there a real or better way of doing this?

Community
  • 1
  • 1
rickbear
  • 128
  • 1
  • 1
  • 8

1 Answers1

-3

if you multiply Random().nextFloat() by 10 it will give you a number from 0 to 9 which are the base numbers in the numeral system, so number 10 doesn't really exist but it's a combination of two base numbers, so you will never be able to get it as a random number, but if you really need it I would go with your second option.

Euclides Mulémbwè
  • 1,677
  • 11
  • 18