- Class Math
- IEEE 754 Recommended Operations
- Генерируем случайное число Java
- Генерация случайных чисел с помощью класса Math
- Случайные числа в заданном диапазоне
- Случайное двойное число в заданном диапазоне
- Случайное целое число в заданном диапазоне
- Генерация случайных чисел с помощью класса Random
- Генерируем случайное число в Java 8 - особенности
- Заключение
- Class Random
Class Math
The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.
Unlike some of the numeric methods of class StrictMath , all implementations of the equivalent functions of class Math are not defined to return the bit-for-bit same results. This relaxation permits better-performing implementations where strict reproducibility is not required.
By default many of the Math methods simply call the equivalent method in StrictMath for their implementation. Code generators are encouraged to use platform-specific native libraries or microprocessor instructions, where available, to provide higher-performance implementations of Math methods. Such higher-performance implementations still must conform to the specification for Math .
The quality of implementation specifications concern two properties, accuracy of the returned result and monotonicity of the method. Accuracy of the floating-point Math methods is measured in terms of ulps, units in the last place. For a given floating-point format, an ulp of a specific real number value is the distance between the two floating-point values bracketing that numerical value. When discussing the accuracy of a method as a whole rather than at a specific argument, the number of ulps cited is for the worst-case error at any argument. If a method always has an error less than 0.5 ulps, the method always returns the floating-point number nearest the exact result; such a method is correctly rounded. A correctly rounded method is generally the best a floating-point approximation can be; however, it is impractical for many floating-point methods to be correctly rounded. Instead, for the Math class, a larger error bound of 1 or 2 ulps is allowed for certain methods. Informally, with a 1 ulp error bound, when the exact result is a representable number, the exact result should be returned as the computed result; otherwise, either of the two floating-point values which bracket the exact result may be returned. For exact results large in magnitude, one of the endpoints of the bracket may be infinite. Besides accuracy at individual arguments, maintaining proper relations between the method at different arguments is also important. Therefore, most methods with more than 0.5 ulp errors are required to be semi-monotonic: whenever the mathematical function is non-decreasing, so is the floating-point approximation, likewise, whenever the mathematical function is non-increasing, so is the floating-point approximation. Not all approximations that have 1 ulp accuracy will automatically meet the monotonicity requirements.
The platform uses signed two’s complement integer arithmetic with int and long primitive types. The developer should choose the primitive type to ensure that arithmetic operations consistently produce correct results, which in some cases means the operations will not overflow the range of values of the computation. The best practice is to choose the primitive type and algorithm to avoid overflow. In cases where the size is int or long and overflow errors need to be detected, the methods addExact , subtractExact , multiplyExact , toIntExact , incrementExact , decrementExact and negateExact throw an ArithmeticException when the results overflow. For the arithmetic operations divide and absolute value, overflow occurs only with a specific minimum or maximum value and should be checked against the minimum or maximum as appropriate.
IEEE 754 Recommended Operations
The 2019 revision of the IEEE 754 floating-point standard includes a section of recommended operations and the semantics of those operations if they are included in a programming environment. The recommended operations present in this class include sin , cos , tan , asin , acos , atan , exp , expm1 , log , log10 , log1p , sinh , cosh , tanh , hypot , and pow . (The sqrt operation is a required part of IEEE 754 from a different section of the standard.) The special case behavior of the recommended operations generally follows the guidance of the IEEE 754 standard. However, the pow method defines different behavior for some arguments, as noted in its specification. The IEEE 754 standard defines its operations to be correctly rounded, which is a more stringent quality of implementation condition than required for most of the methods in question that are also included in this class.
Генерируем случайное число Java
При разработке приложений часто нужно генерировать случайные числа. Java предоставляет для этого классы java.lang.Math и java.util.Random . В этой статье я расскажу о нескольких способах генерации случайных чисел и приведу конкретные примеры реализации.
Генерация случайных чисел с помощью класса Math
Чтобы сгенерировать случайное число Java предоставляет класс Math, доступный в пакете java.util. Этот класс содержит статичный метод Math.random(), предназначенный для генерации случайных чисел типа double .
Метод random( ) возвращает положительное число большее или равное 0,0 и меньшее 1,0. При вызове данного метода создается объект генератора псевдослучайных чисел java.util.Random.
Math.random() можно использовать с параметрами и без. В параметрах задается диапазон чисел, в пределах которого будут генерироваться случайные значения.
Пример использования Math.random():
public static double getRandomNumber()
Метод getRandomNumber( ) использует Math.random() для возврата положительного числа, которое больше или равно 0,0 или меньше 1,0 .
Результат выполнения кода:
Double between 0.0 and 1.0: SimpleRandomNumber = 0.21753313144345698
Случайные числа в заданном диапазоне
Для генерации случайных чисел в заданном диапазоне необходимо указать диапазон. Синтаксис:
(Math.random() * ((max - min) + 1)) + min
Разобьем это выражение на части:
- Сначала умножаем диапазон значений на результат, который генерирует метод random().Math.random() * (max — min)возвращает значение в диапазоне [0 , max- min], где max не входит в заданные рамки. Например, выражение Math.random()*5 вернет значение в диапазоне [0 , 5], в который 5 не входит.
- Расширяем охват до нужного диапазона. Это делается с помощью минимального значения.
(Math.random() * ( max - min )) + min
Но выражение по-прежнему не охватывает максимальное значение.
- Чтобы получить максимальное значение, прибавьте 1 к параметру диапазона (max — min). Это вернет случайное число в указанном диапазоне.
double x = (Math.random()*((max-min)+1))+min;
Существуют различные способы реализации приведенного выше выражения. Рассмотрим некоторые из них.
Случайное двойное число в заданном диапазоне
По умолчанию метод Math.random() при каждом вызове возвращает случайное число типа double . Например:
public static double getRandomDoubleBetweenRange(double min, double max)
Вы можете вызвать предыдущий метод из метода main, передав аргументы, подобные этому.
System.out.println("Double between 5.0 and 10.00: RandomDoubleNumber = "+getRandomDoubleBetweenRange(5.0, 10.00));
System.out.println("Double between 5.0 and 10.00: RandomDoubleNumber = "+getRandomDoubleBetweenRange(5.0, 10.00));
Случайное целое число в заданном диапазоне
Пример генерации случайного целочисленного значения в указанном диапазоне:
public static double getRandomIntegerBetweenRange(double min, double max)
Метод getRandomIntegerBetweenRange() создает случайное целое число в указанном диапазоне. Так как Math.random() генерирует случайные числа с плавающей запятой, то нужно привести полученное значение к типу int. Этот метод можно вызвать из метода main, передав ему аргументы следующим образом:
System.out.println("Integer between 2 and 6: RandomIntegerNumber highlight" data-hscroll>Integer between 2 and 6: RandomIntegerNumber = 5Примечание . В аргументах также можно передать диапазон отрицательных значений, чтобы сгенерировать случайное отрицательное число в этом диапазоне.
Генерация случайных чисел с помощью класса Random
Класс java.util.Random можно применять для генерации случайных чисел различных типов: int, float, double, long и boolean .
Для этого сначала создайте экземпляр класса Random, а затем вызовите один из методов генератора случайных значений: nextInt( ), nextDouble( ) или nextLong( ).
Метод nextInt( ) класса Random принимает граничное целое число и возвращает случайное значение int от 0 (включительно) до указанного предела (не включая).
Пример использования метода nextInt( ):
public static int generateRandomInt(int upperRange)
Пример использования метода nextInt ( ) для генерации целого числа в заданном диапазоне:
public static int generateRandomIntIntRange(int min, int max)
Методы nextFloat ( ) и nextDouble( ) позволяют генерировать числа с плавающей запятой, а также значения типа double в диапазоне от 0,0 до 1,0.
Код для использования обоих методов:
public static double generateRandomDouble() < Random random = new Random(); return random.nextDouble(); >public static float generateRandomFloat()
Генерируем случайное число в Java 8 - особенности
В Java 8 был представлен новый метод класса java.util.Random - ints(). Он возвращает неограниченный поток псевдослучайных значений int. Данный метод позволяет указать диапазон чисел, задав минимальное и максимальное значения.
Пример использования метода Random.ints() для генерации случайных целочисленных значений в указанном диапазоне:
public static int getRandomNumberInts(int min, int max)
Метод getRandomNumberInts( ) генерирует поток случайных целых чисел от min(включительно) и до max (не входит в диапазон).
Метод ints( ) создает IntStream, поэтому будет вызвана функция findFirst( ). Она возвращает объект OptionalInt , который описывает первый элемент этого потока. Затем код вызывает метод getAsInt( ), чтобы вернуть значение int в OptionalInt.
Пример использования метода Random.ints() для генерации потока случайных целочисленных значений:
public static void getStreamOfRandomInts(int num)
Код для вызова предыдущего метода:
System.out.println("Random int stream: RandomIntStreamofSize highlight" data-hscroll>Random int stream: RandomIntStreamofSize = -1861317227 -1205557317 453883217 762357682 1725970934Пример использования метода Random.ints() для генерации потока из диапазона случайных целочисленных значений:
public static void getStreamOfRandomIntsWithRange(int num, int min, int max)
Код для вызова приведенного выше метода:
System.out.println("Random int stream of specified size in range: RandomIntStreamofSizeInRange highlight" data-hscroll>Random int stream of specified size in range: RandomIntStreamofSizeInRange = 2 2 3 4 6Кроме ints( ) существует еще несколько методов, которые были добавлены к классу Random в Java 8. Они могут возвращать последовательный поток случайных чисел. Это:
Заключение
Класс java.util.Random реализует линейный конгруэнтный генератор (LCG). Он отличается быстротой работы. Но при этом он не подходит для использования в режиме реального времени. Например, для генерации уникального идентификатора сессии на сервере, в научных экспериментах, криптографии лотереях и розыгрышах.
Class Random
An instance of this class is used to generate a stream of pseudorandom numbers; its period is only 2 48 . The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald E. Knuth, The Art of Computer Programming, Volume 2, Third edition: Seminumerical Algorithms , Section 3.2.1.)
If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random . Java implementations must use all the algorithms shown here for the class Random , for the sake of absolute portability of Java code. However, subclasses of class Random are permitted to use other algorithms, so long as they adhere to the general contracts for all the methods.
The algorithms implemented by class Random use a protected utility method that on each invocation can supply up to 32 pseudorandomly generated bits.
Many applications will find the method Math.random() simpler to use.
Instances of java.util.Random are threadsafe. However, the concurrent use of the same java.util.Random instance across threads may encounter contention and consequent poor performance. Consider instead using ThreadLocalRandom in multithreaded designs.
Instances of java.util.Random are not cryptographically secure. Consider instead using SecureRandom to get a cryptographically secure pseudo-random number generator for use by security-sensitive applications.