How can I generate a random whole decimal number between two specified variables in java, eg x = -1 and y = 1 would output 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 should include 1 and -1 ([-1,1]) . And give one decimal number after point.
Random r = new Random();
double random = (r.nextInt(21)-10) / 10.0;
Will give you a random number between [-1, 1] with stepsize 0.1.
And the universal 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 doubles with step size 0.1 between [min, max].
If you just want between -1 and 1, inclusive, in .1 increments, then:
Random rand = new Random();
float result = (rand.nextInt(21) - 10) / 10.0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.