隨機數生成器java實現
/**
設計一個隨機數生成器,可以產生給定平均概率的隨機證書序列。
即輸入一個概率比如:0.9
然後輸入要求的概率樣本個數比如:1000
輸出一個接近所輸入的0.9的概率數(要求樣本數越大越接近輸入的概率)
*/
import java.util.Date;
import java.util.Scanner;
public class Random {
private int seed;
private int multiplier = 2743;
private int addOn = 5923;
public Random(boolean pseudo){
if(pseudo){
this.seed = 1;
}else{
seed = (int)(new Date().getTime()%Integer.MAX_VALUE);
}
}
public double randomReal(){
double max = Integer.MAX_VALUE + 1.0;
double temp = reseed();
if(temp < 0) {
temp = temp + max;
}
return temp/max;
}
public int randomInteger(int low, int high){
if(low>high){
return randomInteger(high,low);
}else{
return ((int)((high-low) * randomReal())) + low;
}
}
public int poisson(double mean){
double limit = Math.exp(mean * -1);
double product = randomReal();
int count = 0;
while(product > limit){
count ++;
product = product * randomReal();
}
return count;
}
private int reseed(){
this.seed = seed*multiplier+addOn;
return this.seed;
}
}
class MainApplication{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("請輸入概率平均值:");
double mean = scanner.nextDouble();
System.out.println("請輸入產生隨機整數的個數:");
int count = scanner.nextInt();
Random random = new Random(false);
int sum =0;
System.out.println("產生隨機整數序列");
for(int i=0; i<count; i++){
int num = random.poisson(mean);
sum += num;
System.out.print(num + " ");
if((i+1)%40 == 0){
System.out.println();
}
}
System.out.println();
System.out.println("隨機整數序列平均值是:" + sum*1.0/count);
}
}
//測試兩組資料
//第一組:
//第二組: