Random Integer Generation
Question
:
How do I write a Java program that generates random numbers within
limits, such as 1 to 100, or 1 to 1000?
Answer
:
The java.util package includes a Random class which will generate a
sequence of pseudo-random numbers. Pseudo-random number sequences
appear to have a random distribution, but have a definite order.
Given the same seed, a pseudo-random number generator will always
produce the same sequence of numbers. Therefore, you should
initialize the Random class with as random a seed as possible. Using
the current time as a seed is often sufficient.
However, when a
pseudo-random number sequence is exhausted, it wraps around and starts
again from the beginning. Consequently, for long-lived applications
that generate many random numbers over time, you will want to
periodically reseed your random generator.
The Random class does not provide a generic means of generating random
integers within a specific range. Rather, it generates a uniformly
distributed set of values between 0 and some upper bound. For doubles
and floats it generates a value between 0 and 1. You can use this to
generate arbitrary ranges of random integers. The following example
program provides a random integer generating class that takes care of
converting a random double into a random integer within a specific
range. It also takes care of reseeding the random number generator
after the sequence has been in use for a long time.
import java.util.*;
public final class RandomIntGenerator {
public static final int DEFAULT_MIN_RANGE = 1;
public static final int DEFAULT_MAX_RANGE = 100;
int _minRange, _maxRange, _range;
long _numCalls;
Random _random;
public RandomIntGenerator() {
this(DEFAULT_MIN_RANGE, DEFAULT_MAX_RANGE);
}
public RandomIntGenerator(int minRange, int maxRange) {
_random = new Random(System.currentTimeMillis());
setRange(minRange, maxRange);
_numCalls = 0;
}
public void setRange(int minRange, int maxRange) {
_minRange = minRange;
_maxRange = maxRange;
_range = maxRange - minRange + 1;
}
public int nextInt() {
double d;
d = ((double)_range)*_random.nextDouble();
if(++_numCalls == Integer.MAX_VALUE) {
// The pseudo-random number sequence is sufficiently
// exhausted that it is time to switch to a new seed.
_numCalls = 0;
_random.setSeed(System.currentTimeMillis());
}
return (_minRange + (int)d);
}
public static final void main(String[] args) {
RandomIntGenerator randomInt;
randomInt = new RandomIntGenerator();
for(int i = RandomIntGenerator.DEFAULT_MIN_RANGE;
i <= RandomIntGenerator.DEFAULT_MAX_RANGE; ++i)
System.out.println(randomInt.nextInt());
}
}
分享到:
相关推荐
- Huge prime number generation, factoring and cryptographically secure random number generation (a.o. Blum-Blum-Shub). True random number data from an internet server. - Diffie-Hellman key exchange ...
5. **Random Number Generation**: Secure random number generation is vital for generating cryptographic keys. Algorithms for generating random numbers and ensuring their quality are important. 6. **...
At each step, the genetic algorithm selects individuals at random the current population to be parents and uses them to produce the children for the next generation. Over successive generations, the ...
Finally, you’ll learn the current quantum algorithms for entanglement, random number generation, linear search, integer factorization, and others. You’ll peak inside the inner workings of the Bell ...
random number generation system, which is used in a part of the key generation process, will be re-initialized during runtime. This is done on purpose, as it makes it much harder to abuse this tool...
12. 随机数生成功能(Random Number Generation):生成随机数,用于模拟或其他需要随机性的应用场景。 13. 运动控制功能(Motion Control Functions):涉及到加速度和速度的计算,用于运动控制系统。 14. 数据...
- **Random Number Generation:** - `import random`: Functions for generating random numbers. ##### 1.2 Sequences (Lists are mutable, Tuples and Strings are immutable) - **List Creation:** - `s = l ...
random 10 integers 4. each integer contains 8 digits 5. prints file generation timing statistics per file and total Step 2: Merge all numbers from some files if CLI parameter is “-s [foler_name]" 1. ...
8. **随机数库增强(Improved Random Number Generation)** 提供了更多的随机数引擎和分布,使得生成随机数更加灵活和高效。 9. **`std::integer_sequence`和`std::index_sequence`** 这些工具类模板简化了元...
有了这些定量指标后,研究者利用随机混合整数规划方法(Random Mixed Integer Programming),提出了计算这些指标的具体方法。 具体而言,通过随机混合整数规划方法,可以在保证智能楼宇正常运行的前提下,充分发掘...
Random Number Generation 随机数生成 - **Factoring and Primality Testing 因子分解/质数判定**:确定一个数是否为质数以及将其分解为质因数的技术。 - **Arbitrary Precision Arithmetic 高精度计算**:使用任意...
5.2.1 Effect of Integer Carrier Frequency Offset (IFO) 159 5.2.2 Effect of Fractional Carrier Frequency Offset (FFO) 160 5.3 Estimation Techniques for STO 162 5.3.1 Time-Domain Estimation Techniques ...
6. An Integer Square Root Algorithm C 387 Christopher J. Musial 7. Fast Approximation to the Arctangent 389 Ron Capelli CONTENTSxiv CONTENTS 8. Fast Sign of Cross Product Calculation C 392 Jack Ritter...
- Random number generation using the `random` module. - Conditional statements (`if`, `elif`, `else`) for handling user input. - User input validation. 2. **Summing Numbers** - **Objective:** ...
% divider - Find dividers of integer such that product equals integer. % dwindow - Derive a window. % integ - Approximate integral. % integ2d - Approximate 2-D integral. % izak - Inverse Zak ...
* Document integer problem in OpenSC and implement workaround * Improve entersafe profile to support private data objects New in 0.11.9; 2009-07-29; Andreas Jellinghaus * New rutoken_ecp driver by ...
命令式随机数据生成器和快速检查 您可以使用Rantly生成随机测试数据,并使用其Test :: Unit扩展名进行基于属性的测试。 Rantly基本上是递归下降解释器,其每个...> Rantly { [ integer , float ] } # same as Rantly.v