3

How can I generate a random whole decimal number between two specified variables in java, e.g. 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.

Omid7
  • 3,154
  • 4
  • 15
  • 12
  • 1
    Did you check http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java ? – Alexis C. Dec 17 '14 at 17:52
  • 3
    Tip: it is the same as generating random integers in range `-10`...`10` and dividing them by `10.` – Pshemo Dec 17 '14 at 17:55

2 Answers2

8
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].

amithgc
  • 6,167
  • 6
  • 29
  • 38
Marv
  • 3,517
  • 2
  • 22
  • 47
  • To use this answer as a general model, see that the `-1` is the starting number and the `2.0` is the total range. – snickers10m Dec 17 '14 at 17:55
  • 3
    The OP seems to want 0.1 and 0.2 to be possible results but not (say) 0.1234. – Alan Stokes Dec 17 '14 at 17:55
  • 1
    (1) you don't need casting result of `int/double` to double because it *is* double, (2) this way you will never get `1.0` since `nextInt(20)` can return max 19. – Pshemo Dec 17 '14 at 18:00
  • Your original way worked, you just needed to round after `Math.round(randomDouble * 10) / 10d` – yate Dec 17 '14 at 18:02
  • 1
    Yes, `nextInt(21)` will generate values in range `0, 20` (both inclusive) so after `-10` range will change to `-10,10` and after dividing by `10.0` to `-1.0, 1.0`. – Pshemo Dec 17 '14 at 18:03
2

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;
Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
WannabeCoder
  • 498
  • 1
  • 5
  • 20