Java Random () rounding

I use Java Random to generate random numbers: 1.0, 1.1 - 10

Random random = new Random();
return (double) ((random.nextInt(91) + 10) / 10.0);

When I printed a lot of these numbers (2000), I noticed that 1.0 and 10 are much less printed than everyone else (repeated 20 times, each time). Most likely because 0.95-0.99 and 10.01-10.04 are not generated.

Now I read a lot of threads about this, but it still leaves me with the following question:

If these numbers will represent estimates, for example, you cannot get lower than 1 and higher than 10 here, would it be legal to extend the range from 0.95 to 10.04?

Random random = new Random();
return Double.valueOf((1005-95) / 100);
+4
source share
2 answers

To create a random value between 1.1 and 10, use the following code:

  double min = 1.1d;
  double max = 10d;
  Random r = new Random();
  double value = min + (max - min) * r.nextDouble();

After that you can use Math.floor(value)too round result

+1

, , 0,95-0,99 10,01-10,04 .

. ints 10 100 . . nextInt ; .

,

Random random = new Random();
return (double) ((random.nextInt(91) + 10) / 10.0);

. , , , , .

, 91. , . ( , 10 - , , 10 → 1,0, 11 → 1,1... 99 → 9,9 100 → 10,0 , )

    Random random = new Random();

    int[] measure = new int[101];
    for (int i = 0; i < 10000; i++) {

        int number =  (random.nextInt(91) + 10);
        measure[number]++;         

    }
    for (int i = 0; i < 101; i++) {

        System.out.println(i + " count: " + measure[i]);

    }

, 10 100 , .

+1

Source: https://habr.com/ru/post/1687704/


All Articles