Java math random или random

Math.random() v/s Random class [duplicate]

The Math class in Java has a method, Math.random() which returns a pseudorandom number between 0 and 1.
There is also a class java.util.Random which has various methods like nextInt() , nextFloat() , nextDouble() , nextLong() etc. My question is that if I want to get a random number in a range (say, 30-70), then which way should I go? The factors under consideration are speed and randomness.

3 Answers 3

If you look at the implementation of Math.random() , you’ll see that it uses an instance of the Random class :

public static double random() < return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble(); >private static final class RandomNumberGeneratorHolder

Therefore the randomness would be the same.

That said, since you need an int and not a double , you’d better use the nextInt method of the Random class, since it would save you the multiplication and casting of a double to int .

Random rnd = new Random(); int num = rnd.nextInt(41)+30; 

I personally would go with the random class, because, in my opinion, it’s way easier to use and to influence with parameters, for example for a random number between 30-79

Random r = new Random(); int i = r.nextInt(40)+30;

I hope that helped at least a bit

Math.random() does rely on the Random class. Depending on the case and data type you are using you can use either. For an int Random.nextInt() would probably be the best choice.

Speaking of randomness, a more secure random class is SecureRandom. SecureRandom does not rely on the system time unlike Random, so if your application has a security element to it definitely use SecureRandom. Same method names, except

SecureRandom secureRandom = new SecureRandom() instead of

Random random = new Random() .

Linked

Hot Network Questions

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Генерация случайных чисел в Java

Генерация случайных чисел в Java — важная и нужная тема. Действительно, она Вам понадобится неисчислимое количество раз.

  • при заполнении массива случайными числами
  • при перетасовке колоды карт
  • при выборе случайного элемента из последовательности
  • и т.д.
Читайте также:  Php month name language

Давайте же разберемся с этой темой.

Существует несколько способов как сгенерировать случайное число. В этой статье мы рассмотрим генерацию чисел с помощью Math.random()

В библиотеке классов Java есть пакет java.lang, у которого есть класс Math, а у класса Math есть метод random() . См. картинку ниже в помощь.

Генерация случайных чисел в Java_vertex

Так вот, при каждом вызове Math.random() c помощью специального алгоритма (за определенной инструкцией) генерируется случайное число. Можно ли предсказать какое число будет сгенерировано? Теоретически это возможно, но это очень трудно сделать. А поскольку все-таки существует небольшая вероятность предсказать, какое же число будет сгенерировано алгоритмом, такие числа принято называть не случайными, а псевдослучайными.

Вы должны знать 3 момента:

1. По умолчанию Math.random() генерирует случайные вещественные числа из промежутка [0;1), то есть от нуля включительно до 1 исключительно.

«До 1 исключительно» — это значит, что Math.random() не может сгенерировать число 1. Разве что 0,999 — то есть любое число меньше 1.Попробуйте запустить на своем компьютере вот этот код и сами увидите, что в консоль будут выводиться вещественные числа от 0 до любого числа, меньше 1.

Источник

How to generate random numbers in Java

Generating random numbers in Java is a common requirement while working on Java application. In this article, we will look at how to generate random numbers in Java.

How to Generate Random Numbers in Java

Normally, we came up with 2 types of requirements to generate a random number or generate a random number within a range. Java supports random number generation through ThreadLocalRandom , java.lang.Math and java.util.Random classes. Let’s see what are the different options and how to generate random numbers in Java.

1. Generate Random Number Using ThreadLocalRandom

If you are using Java 1.7 or later, ThreadLocalRandom should be your standard way to generate the random numbers in Java. There can be 2 variations while generating a random numbers in Java or any other language.

package com.javadevjournal.date; import java.util.concurrent.ThreadLocalRandom; public class RandomNumberGeneration < public static void main(String[] args) < int lowerBound = 4; int upperBound = 20; int random_int = ThreadLocalRandom.current().nextInt(); //returns pseudorandom value System.out.println(random_int); //output will be different on different machine (2063277431 while running example); /*generate random int within given range between 0 upper given bound. * The upper bound is non exclusive i'e it will not be counted while generating the * random number. * */ int random_int_with_upper_bound = ThreadLocalRandom.current().nextInt(upperBound); System.out.println(random_int_with_upper_bound); // 6 while we were running the code. /** * Generate random number with a given range of lower and upper bound. */ int random_int_range = ThreadLocalRandom.current().nextInt(lowerBound, upperBound + 1); System.out.println(random_int_range); // 18 while we were running the code. >>

Keep in mind the following important point while using the ThreadLocalRandom .

  1. If you don’t provide lower-bound, it will take lower bound as 0.
  2. upper bound is non exclusive, you need to be careful if you want to add upper range in the random number generation (add 1 to the upper range to include it).
  3. We don’t need explicit initialize with the ThreadLocalRandom class.
  4. If the bound is
  5. If lower-bound is greater than or equal to upper bound, class will throw IllegalArgumentException .
int lowerBound = 4; int upperBound = 3; /** * These will throw IllegalArgumentException. */ ThreadLocalRandom.current().nextInt(lowerBound, upperBound); ThreadLocalRandom.current().nextInt(0);

The nextDouble() and nextFloat() method allows generating the float and double values.It works similar to the above example and we can pass the lower and upper bound while generating the random double or float numbers.

ThreadLocalRandom.current().nextDouble(); ThreadLocalRandom.current().nextDouble(1.0, 34.0); ThreadLocalRandom.current().nextFloat();

2. Using Random Class

If you are not using Java 1.7 or higher, we can use the java.util.Random class to generate random numbers in Java.Here are some details for this class:

  1. nextInt(upperBound) – Generate random int between 0 and upperbound -1 ;
  2. nextFloat() – Generate float between 0.0 to 1.0 .
  3. nextDouble() – Generate double between 0.0 to 1.0 .
package com.javadevjournal.date; import java.util.Random; public class RandomNumberGeneration < public static void main(String[] args) < int min = 1; int max = 67; Random random = new Random(); //Get random int between 46 int randomInt = random.nextInt(max); /* If we want to include 67 in the range, add 1 to the upper bound i.e max+1 generate random int between [0- 67] */ int upperBoundInt = random.nextInt(max + 1); //another variation int randomNum = random.nextInt((max - min) + 1) + min; //Double random number double randomDouble = random.nextDouble(); float randomFloat = random.nextFloat(); >>

3. Using Math.random

We can use Math.random in case we only need integer or float random values.Here is a sample code from Math.random class:

double random = Math.random();

This will return a positive double value that is greater than or equal to 0.0 and less than 1.0 .In many use-cases, we may like to generate a random number within given range.One of the option to do that is using the following expression

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

  1. Math.random() generates a double value in the range [0,1) .
  2. To get a specific range of values, We should multiple by the magnitude of the range of values we want covered ( * ( Max — Min ) ).
  3. Shift this range up to the range that you are targeting. You do this by adding the min value (last part of expression +min )
public class RandomNumberGeneration < public static void main(String[] args) < double min = 1; double max = 67; /* Generate random number with in given range */ double random = (int)(Math.random() * ((max - min) + 1)); System.out.println(random); >>

4. Math.random() versus Random.nextInt(int)

If you are only interested in getting the int as the random number, you should choose the Random.nextInt(n) as this option is more efficient and less biased.Here are some of the advantages of using Random.nextInt over Math.random()

  1. Math.random() uses Random.nextDouble() internally. It’s better to use the original one than routing through it.
  2. Random.nextInt(n) is repeatable. We can create 2 different Random objects by passing same seed.
  3. Math.random() also requires about twice the processing and is subject to synchronization.

5. Generate Random numbers using Java 8

Though most of the cases can be easily fulfilled using ThreadLocalRandom , however , if you are more interested in how to generate random numbers in Java 8 , here are few options to accomplish it using Java 8

import java.util.Random; import java.util.SplittableRandom; import java.util.stream.IntStream; public class RandomNumberGeneration < public static void main(String[] args) < int min = 1; int max = 67; int size=50; /* return int between the specified * min range (inclusive) and the specified upper bound (exclusive). */ int randomInt= new SplittableRandom().nextInt(min, max); //TO return stream of random values IntStream stream = new SplittableRandom().ints(size, min, max); // to generate int[] int[] randomArray= new SplittableRandom().ints(size, min, max).toArray(); int[] randomArray1= new Random().ints(size, min,max).toArray(); >>

Summary

In this article, we saw how to generate random numbers in Java. We saw how to use the ThreadLocalRandom to generate the random numbers if you are using Java 1.7 or higher version or how to use other options to generate random numbers if still using Java 1.6 or lower version. There are few external libraries which can be used to generate random numbers in Java, however we should use the built in Java methods as they can work for all types of use cases.Here is a decision chart for you which can help to decide among the different options.

Источник

Оцените статью