I want to generate Random Float numbers between Interval [0,1]. The generated Random values will be compared with an input from a file. The content of the File is a probability (float values) and hence they are in range[0,1] and it looks like:
0.55
0.14
0.005
0.870
0.98
0
1
I am reading this File and storing probability values into a DoubleList. Now I want to generate a float Random Number between [0,1]. As you see the file have probability values upto 1 digit, 2 digits decimal and 3 digits decimal as well. I am using following Code:
public static double randomNumberGenerator()
{
double rangeMin = 0.0f;
double rangeMax = 1.0f;
Random r = new Random();
double createdRanNum = rangeMin + (rangeMax - rangeMin) * r.nextDouble();
return(createdRanNum);
}
The random float value generated should be also be like Probabilities values (like generated upto the maximal decimal digits as in the file). How can I restrict the generated decimal digits?
I checked the following Link: Java random number between 0 and 0.06 . People suggested Int number generation and then did the double division by 100. Is this the good way? Can't we restrict the decimal generated directly?
PS: If I compare the random generated number from the above code with the double values from File, would there be some memory fall issues in the DoubleList?
You could just use Java Random class :
Random rand = new Random();
float f = rand.nextFloat()
which returns the random float number between 0.0f (inclusive) and 1.0f(exclusive).
To round the result of the nextFloat()
you could just use an helper method like the following :
public static float round(float d, int decimalPlace) {
BigDecimal bd = new BigDecimal(Float.toString(d));
bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
return bd.floatValue();
}