Generating decimal random numbers in Java in a specific range?

How can I generate a random integer decimal number between two specified variables in java, for example x = -1 and y = 1 outputs any of -1.0, -0.9, -0.8, -0.7, ..., 0, 0.1, 0.2, 0.3 , 0.4, 0.5, 0.6, 0.7, 0.9, 1.0?

Note: it must include 1 and -1 ([-1,1]). And give one decimal number after the dot.

+3


source to share


2 answers


Random r = new Random();
double random = (r.nextInt(21)-10) / 10.0;

      

Gives you a random number between [-1, 1] in 0.1 increments.

And a generic method:



double myRandom(double min, double max) {
    Random r = new Random();
    return (r.nextInt((int)((max-min)*10+1))+min*10) / 10.0;
}

      

will return doublings in 0.1 increments between [min, max].

+7


source


If you just want -1 to 1 inclusive, in .1 increments, then:



Random rand = new Random();
float result = (rand.nextInt(21) - 10) / 10.0;

      

+2


source







All Articles