您的位置:首页 > 编程语言 > Java开发

Java生成有概率随机数(可自定义随机数长度及概率)

2018-02-11 15:16 429 查看
    由于项目工作需求,需要一种随机数生成的法,可自定义概率和长度。遍观网上各大平台,无法找到满足需求的方法,于是动手自己写了一个实现类。手拙,望批评建议。

1、自定义MathRandom类实现

import java.util.ArrayList;
import java.util.List;
public class MathRandom
{
private List<Double> probability;//随机数生成的概率列表
private int high;//随机数的范围(0-high)

public MathRandom(int block) {
this.probability = new ArrayList<Double>(block);
this.high = block;
}

/*
* 初始化概率表,判断概率之和是否为1
*/
public boolean init(List<Double> prob) {
double count= 0 ;
for(double i : prob)
count = count + i;
if(count == 1)
{
for(int i = 0 ;i< prob.size();i++)
this.probability.add(prob.get(i));
return true;
}
else
return false;
}

/*
* 生成随机数,范围(0-high)
*/
public int random() {
if(this.high<=0)
return -1;
else {
double  randomNumber = Math.random();
double count = 0;
int out = -1 ;
for(int i = 0;i< this.high ; i++)
{
count =count + this.probability.get(i);

if(randomNumber <= count)
{
out = i;
break;
}
else
{
continue;
}
}
return out;
}
}

/*
* 获取(0-high)之间的概率
*/
public double getProbability(int k) {
return probability.get(k);
}

public int getHigh() {
return high;
}

}

2、测试的主函数

/*
* 测试主函数
*/
public static void main(String[] args) {
MathRandom cMathRandom = new MathRandom(4);

ArrayList<Double> cArrayList = new ArrayList<Double>(4);
cArrayList.add(0.5);
cArrayList.add(0.3);
cArrayList.add(0.15);
cArrayList.add(0.05);

cMathRandom.init(cArrayList);//初始化随机数概率

int[] count = new int[4] ;

for(int i = 0 ; i < 10000 ; i ++) {
int k = cMathRandom.random();
switch (k) {
case 0:
count[0]++;
break;
case 1:
count[1]++;
break;
case 2:
count[2]++;
break;
case 3:
count[3]++;
break;
default:
break;
}
}

int num = 0 ;
for(int j = 0 ; j < 4 ; j ++) {
System.out.println("随机数 "+j+"  \t设定的概率:"+cArrayList.get(j)+"\t 对应的数量:"+count[j] );
num+=count[j];
}
System.out.println("所有随机数数量之和:"+num);

}

3、总结

    具体测试可以将测试主函数放入类里直接运行,也可以单独拿出测试,看个人喜好。由于第一次写此类博客,如有不足之处,希望多家批评建议,谢谢。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 随机数