There are two means of generating random (really pseudo-random) numbers :
the Random class generates random integers, doubles, longs and so on, in various ranges.
the static method Math.random generates doubles between 0 (inclusive) and 1 (exclusive).
To generate random integers :
do not use Math.random (it produces doubles, not integers)
use the Random class to generate random integers between 0 and N.
To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number. See also the related Sun Tech Tip.
Another alternative is SecureRandom, a cryptographically strong subclass of Random.
Example 1
import java.util.Random;
/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
public static final void main(String... aArgs){
log("Generating 10 random integers in range 0..99.");
//note a single Random object is reused here
Random randomGenerator = new Random();
for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGenerator.nextInt(100);
log("Generated : " + randomInt);
}
log("Done.");
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
Example run of this class :
Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.
Example 2
This example generates random integers in a specific range.
import java.util.Random;
/** Generate random integers in a certain range. */
public final class RandomRange {
public static final void main(String... aArgs){
log("Generating random integers in the range 1..10.");
int START = 1;
int END = 10;
Random random = new Random();
for (int idx = 1; idx <= 10; ++idx){
showRandomInteger(START, END, random);
}
log("Done.");
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
if ( aStart > aEnd ) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
//get the range, casting to long to avoid overflow problems
long range = (long)aEnd - (long)aStart + 1;
// compute a fraction of the range, 0 <= frac < range
long fraction = (long)(range * aRandom.nextDouble());
int randomNumber = (int)(fraction + aStart);
log("Generated : " + randomNumber);
}
private static void log(String aMessage){
System.out.println(aMessage);
}
}
An example run of this class :
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
Example 3
This example generates random floating point numbers in a Gaussian (normal) distribution.
import java.util.Random;
/**
Generate pseudo-random floating point values, with an
approximately Gaussian (normal) distribution.
Many physical measurements have an approximately Gaussian
distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {
public static void main(String... aArgs){
RandomGaussian gaussian = new RandomGaussian();
double MEAN = 100.0f;
double VARIANCE = 5.0f;
for (int idx = 1; idx <= 10; ++idx){
log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
}
}
private Random fRandom = new Random();
private double getGaussian(double aMean, double aVariance){
return aMean + fRandom.nextGaussian() * aVariance;
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}
An example run of this class :
Generated : 99.38221153454624
Generated : 100.95717075067498
Generated : 106.78740794978813
Generated : 105.57315286730545
Generated : 97.35077643206589
Generated : 92.56233774920052
Generated : 98.29311772993057
Generated : 102.04954815575822
Generated : 104.88458607780176
Generated : 97.11126014402141
分享到:
相关推荐
Java Program To Generate Random Numbers
* Generate random numbers * Simple calculations of statistical data * Analysis of correlation and regression * Multidimensional methods * Variance analysis * Analysis of the time series * Non-...
采用C++语言产生伪随机数,可以选择产生整数随机数和小数随机数 (Generating pseudo-random numbers in C++ language ,You can choose to generate integers, random numbers, and decimal random numbers)
This test will generate random numbers of calls to some getpid syscalls, then establish an mmap for a group of events that are created to monitor the syscalls.
# generate random numbers and send them to "check" and "normal" [random] plugin = source.random flow = -> check, normal schedule = * * * * * # filter numbers from "random" that are > 0.5 and send to ...
随机过程中产生随机数的matlab实现,里面是产生正态、泊松、伯努利的代码和文档,还有对各种随机数的分析
A C code to generate random numbers and find its histogram.
This report describes the transformation techniques to generate non-uniform random numbers with the exponential, normal and arbitrary distributions. These are generated by random number generator, ...
Learn the uses of Pseudo Random Numbers Create reusable algorithm designs for PCG Evaluate the data structures for PCG Develop smaller games with larger amounts of content Generate content instead of ...
Monte Carlo means using random numbers in scientific computing. More precisely, it means using random numbers as a tool to compute something that is not random. For example1 , let X be a random ...
用labview实现的正态分布的随机数并生成对应的直方图(Achieved with labview normally distributed random numbers and generate the corresponding histogram)
随机数组 生成随机数数组 安装 npm install random-...//Generate array of size 10 and round numbers between 1 and 10 random ( 1 , 10 ) . oned ( 10 , { round : true } ) ; 生成随机数数组,而函数为false。
FSIM has the ability to generate pseudo-random patterns with various starting seeds and fault-simulate them. You can use this capability to test your own code on pseudo-random numbers, and use it as a...
The book begins with fundamental questions regarding random numbers and how to use algorithms to generate them. Subsequent chapters demonstrate efficient computation of single-precision and double-...
In the classic implementation of shuffled frog-... However, the implementation has to generate random number many times and thus lead to remarkable time consumption. To solve this problem, in this p
1) On first start, press 'Start' to generate some random data. 2) Select size, quantity and number base of Prime numbers you need and press the 'Generate' button.
1.Number of rows2.Number of columns您的函数应执行以下操作: 1.Generate a multi-dimensional array with the specified number of rows and columns in the array populated with random numbers between 1 and...
from a combination of a few hundred random numbers. Google language translation services, Alexa voice recognition, and self-driving cars all run on deep learning algorithms. Other emergent areas are...