RichardB
RichardB

Reputation: 41

Java Random() rounding off

I'm using Java's 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 1.0 and 10 are significant less printed than all others (repeated 20 times, happened every time). Most likely because 0.95-0.99 and 10.01-10.04 aren't generated.

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

If these numbers would represent grades for example, you can't get lower than a 1 and higher than a 10 here, would it be legit to extend the range from 0.95 up to 10.04?

Random random = new Random();
return Double.valueOf((1005-95) / 100);

Upvotes: 4

Views: 408

Answers (2)

Adam
Adam

Reputation: 3003

This premise

Most likely because 0.95-0.99 and 10.01-10.04 aren't generated.

is wrong. You generate random ints from 10 inclusive to 100 inclusive. Lower fractions and rounding of values does not play into it. Random nextInt is random in the interval; the end cases is not discriminated against.

I think your method

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

Looks correct. I would suggest measuring the anomaly you are experiencing, maybe it is a human bias from when you are merely looking at the output.

Here is some code that measures the actual random generation of the 91 values. It is before the conversion to double which is not ideal.(but I do not see how dividing by 10 does anything else than map values as 10 -> 1.0, 11 -> 1.1 ... 99 -> 9.9 and 100 -> 10.0. A measure of the final result would of course be more desirable)

    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]);

    }

Looking at the results from that code the 10 and 100 values seem to come up as often as any other.

Upvotes: 1

osanger
osanger

Reputation: 2352

To generate 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();

Afterwarsds you can use Math.floor(value) too round your result

Upvotes: 1

Related Questions