Generate random number between two numbers with Math.Random

Asked

Viewed 3,735 times

-1

I need to generate a random number between 1000 and 9999, found the following formula:

(int) (min + Math.random() * (max+1))

Code:

int numeroAleatorio = (int) (1000 + Math.Random() * 10000);
System.out.println("Thread A: " + numeroAleatorio);

But it generated a greater number than 9999, as can be seen in the image below.

Código

  • 2

    Can you put your code as text anyway? It’s bad for people to help this way. I myself didn’t feel like answering because I couldn’t use the code to test the solution I would give.

3 answers

4


The correct formula would be:

((int)(min + Math.random() * (max - min + 1))

Or if you prefer:

Random random = new Random();
return random.nextInt((maximo - minimo) + 1) + minimo;

Your code could be tested like this:

class Main {
    public static void main (String[] args) {
        for (int i = 0; i < 1000; i++) System.out.println((int)(1000 + Math.random() * (10000 - 1000 + 1)));
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

If the intention is to use a concurrent random generator in isolation, just switch to ThreadLocalRandom.

3

The method Math#random returns a double equal to or greater than 0.0 and less than 1.0.

int numeroAleatorio = (int) (1000 + Math.Random() * 10000);

One problem with the code is that the minimum value is not specified, instead the maximum value is multiplied by the value of Math.Random, which may be for example: 0.02 or 0.98, then add the minimum value.

The correct would be to subtract the maximum and minimum value and add 1 (if you want the maximum value to be returned randomly), then multiply by the value of Math.random, finally, just add the minimum value to indicate the beginning of the interval.

public static int numeroAleatorio(int a, int b) {
    final int min = Math.min(a, b);
    final int max = Math.max(a, b);

    return min + (int)(Math.random() * ((max - min) + 1));
}

Note: The casting for int is necessary to truncate the result (due to the Math.random return a double).

If you prefer to use Random#nextInt-int instead of Math#random:

public static int numeroAleatorio2(int a, int b) {
    final int min = Math.min(a, b);
    final int max = Math.max(a, b);

    Random r = new Random();
    return min + r.nextInt((max - min) + 1);
}

To use, just do so:

public static void main (String[] args) throws java.lang.Exception
{
    System.out.println(numeroAleatorio(1000, 9999));
}

See DEMO

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.