传入数值1,上下浮动20% ,得到0.8到1.2之间的数值
/**
* 按上下浮动率百分比转换数值
* @param num 传入的数值
* @param rate 最大上下浮动比例
* 1 20%
* @return 浮动后的结果数值
* @destribute 传入数值1,上下浮动20% ,得到0.8到1.2之间的数值
*/
public static BigDecimal getRatedValue(BigDecimal num,int rate){
BigDecimal rateValue =new BigDecimal(new Random().nextInt(rate)+1).multiply(num).divide(new BigDecimal(100));
double z = Math.random();
if(z>0.5){
return num.add(rateValue).setScale(2, BigDecimal.ROUND_DOWN);
}else{
return num.subtract(rateValue).setScale(2, BigDecimal.ROUND_DOWN);
}
}
传入总数量100,需要的出现的数量1 ,是否是1%的概率
/**
* 获取是否指定概率
* @param sum 总的可能出现数量
* @param num 需要的出现的数量
* 100 ,1 是百分值一 random.nextInt(100);中的100是随机数的上限,产生的随机数为0-99的整数,不包括100。
* @return 获取是否是指定概率
* @destribute 传入总数量100,需要的出现的数量1 ,是否是1%的概率
*/
public static boolean probability(int sum,int num){
int i = ThreadLocalRandom.current().nextInt(sum);
if(i>=0&&i<num){
return true;
}else{
return false;
}
}
//0 1 2... 不限制, 配置每种选项的中奖概率,并获取中奖值
public static Integer probability(List<PrizeCard> list,int cardType){
cardType = 0;//默认是新年卡
//计算总概率
try {
int sum = list.stream().mapToInt(PrizeCard::getCardWeight).sum();
int randomNumber = ThreadLocalRandom.current().nextInt(sum);
int d1 = 0;
int d2 = 0;
for(int i = 0;i<list.size();i++){
d2+=list.get(i).getCardWeight();
if(i == 0){
d1 = 0;
}else{
d1 += list.get(i-1).getCardWeight();
}
if(randomNumber >= d1 && randomNumber < d2){
cardType = list.get(i).getCardType();
break;
}
}
} catch (Exception e) {
//TODO 打印错误日志
e.printStackTrace();
}
return cardType;
}
public static void main(String[] args) {
List<PrizeCard> list = new ArrayList<>();
PrizeCard p1 = new PrizeCard(0,0);
list.add(p1);
/*PrizeCard p2 = new PrizeCard(1,1);
list.add(p2);*/
PrizeCard p3 = new PrizeCard(2,100);
list.add(p3);
for(int i = 0; i < 10000; i++){
int a = probability(list,0);
for(PrizeCard p:list){
if(p.getCardType()==a){
p.setNum(p.getNum()+1);
}
}
}
list.forEach(System.out::println);
}
public class PrizeCard {
private Integer cardType;
private Integer cardWeight;
private Integer num = 0;
public Integer getCardType() {
return cardType;
}
public void setCardType(Integer cardType) {
this.cardType = cardType;
}
public Integer getCardWeight() {
return cardWeight;
}
public void setCardWeight(Integer cardWeight) {
this.cardWeight = cardWeight;
}
public PrizeCard(Integer cardType, Integer cardWeight) {
this.cardType = cardType;
this.cardWeight = cardWeight;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
@Override
public String toString() {
return "PrizeCard{" +
"cardType=" + cardType +
", cardWeight=" + cardWeight +
", num=" + num +
'}';
}
}
java概率工具
最新推荐文章于 2024-05-07 15:21:25 发布