Generate random number between two numbers with Math.random [duplicate]

-2

I need to generate a random number between 1000 and 9999 , I 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 number greater than 9999 , as can be seen in the image below.

    
asked by anonymous 22.10.2016 / 22:01

3 answers

3

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 Ideone {
    public static void main (String[] args) {
        for (int i = 0; i < 1000; i++)
        System.out.println((int)(1000 + Math.random() * (10000 - 1000 + 1)));
    }
}

See working on ideone and on CodingGround .

If you intend to use a concurrent random generator, just switch to ThreadLocalRandom .

    
22.10.2016 / 23:35
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 of the problems of the code is that the minimum value is not indicated, instead the maximum value is multiplied by the value of Math.Random , which can be for example: 0.02 or 0.98 , then the minimum value is added.

The correct one 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));
}
The casting for int is required to truncate the result (due to Math.random returning 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 the following:

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

See DEMO

    
22.10.2016 / 23:54
2

Take a look at:

link

import java.util.concurrent.ThreadLocalRandom;
ThreadLocalRandom.current().nextInt(min, max + 1);
    
22.10.2016 / 22:50