# 伪随机值的概率

Random类以及HashMap类。HashMap类的对象可以存放“键值对”数据，键不可重复。即如果HashMap对象已经有键值对数据，如果再向其添加,HashMap对象将清除先前的键值对数据

https://share.weiyun.com/5RVf0GV

MainClass.java

import java.util.Arrays;

public class MainClass {

public static void main(String args[]){

VerificationRandom verification =

new Verification();

int samples = 100000;//样本空间大小

verification.setSamples(samples);

//返回0至m伪随机数的概率:

int m =10;

double probability[] =

verification.verificationRandom(m);

("样本空间大小"+samples);

("得到0至"+m+"伪随机数的概率");

double sum = 0;

for(double d:probability){

sum += d;

}

Arrays.sort(probability);

("最大概率:"+probability[probability.length-1]);

("最小概率:"+probability[0]);

}

}

IntegerFrequency .java

public class IntegerFrequency {

private int number;

private int count; //number出现的次数

public void setNumber(int m){

number = m;

}

public int getNumber(){

return number;

}

public void setCount(int m){

count = m;

}

public int getCount(){

return count;

}

}

VerificationRandom .java

public interface VerificationRandom {

public void setSamples(int m);//设置样本空间大小

public double [] verificationRandom(int m);

//验证0至m(不包括m)出现的概率是否符合真随机数出的概率

}

VerificationRandom .java

import java.util.Random;

import java.util.HashMap;

public class Verification

implements VerificationRandom{

//存放键值对：键是String，值是IntegerFrequency：

HashMap map;

Random random;

int samples =1000;//样本数

Verification(){

map =

new HashMap();

random = new Random();

}

public void setSamples (int m){

samples = m;

}

public double [] verificationRandom(int m){

double probability[];//存放数字出现的概率

probability = new double[m];

for(int i = 0;i

int n = random.nextInt(m);

IntegerFrequency number =

new IntegerFrequency();

number.setNumber(n);

if(map.containsKey(""+n)){

IntegerFrequency isSave =

map.get(""+n);

isSave.setCount(isSave.getCount()+1);

}

else {

map.put(""+n,number); //散列映射添加键值对

}

}

int k = 0;

while(k

if(map.containsKey(""+k)) {

IntegerFrequency n = map.get(""+k);

int count = n.getCount();

double frequency =

(double)count/samples;

probability[k] = frequency;

}

k++;

}

return probability;

}

}

• 发表于:
• 原文链接https://kuaibao.qq.com/s/20200414A0D8OT00?refer=cp_1026
• 腾讯「云+社区」是腾讯内容开放平台帐号（企鹅号）传播渠道之一，根据《腾讯内容开放平台服务协议》转载发布内容。
• 如有侵权，请联系 yunjia_community@tencent.com 删除。

2021-04-14

2021-04-14

2021-04-14