使用乘法和进位法生成随机数的Java程序
在计算机科学中,乘以进位 (MWC) 是 George Marsaglia 发明的一种方法,用于基于从两个到数千个随机选择的种子值的初始集合生成随机整数序列。 MWC 方法的主要优点是它调用了简单的计算机整数算法,并且可以非常快速地生成具有巨大周期的随机数序列,范围从大约 2 60到 2 2000000 。
例子:
Input : Length = 5
Output: 1581 16 1932 1969 1384
Input : Length = 2
Output: 985 3568
使用的公式:
x(n) = (a*x(n-r) + c(n-1))mod n
c(n) = (a*x(n-r) + c(n-1))/n
where,
- a is any multiplier,
- m is modulus,
- c is carry, and
- r is a initial number of seeds.
Java
// Java Program to generate a random numbers
// Based on Multiply with carry method
import java.util.Random;
public class Main {
public static void main(String args[])
{
int Maximum_Sequence_Elements = 10;
Random random = new Random();
int Base = 2000;
int Multiplier = random.nextInt(Base);
int r = 1;
int[] c = new int[Maximum_Sequence_Elements];
int[] x = new int[Maximum_Sequence_Elements];
c[0] = random.nextInt(Multiplier);
x[0] = random.nextInt(Base);
System.out.print("The random number sequence is: "
+ x[0]);
// generating sequence
for (int i = 1; i < Maximum_Sequence_Elements;
i++) {
x[i]
= (Multiplier * x[i - r] + c[i - 1]) % Base;
c[i]
= (Multiplier * x[i - r] + c[i - 1]) / Base;
System.out.print(" " + x[i]);
}
}
}
输出
The random number sequence is: 508 1021 1549 857 414 1187 1425 1557 1945 1922