java:产生小数位数为2的随机概率,使得和为1(转)

参考https://www.cnblogs.com/kxdblog/p/4197831.html

package com.thesis.Method1;

import java.text.DecimalFormat;


public class MainSolution {


private static final int NUM = 5;
public static void main(String[] args){

for(float f :genProp()){
System.out.println(f );
}
}


public static float[] genProp(){
//产生概率随机数,且让和为1
float[] prop =new float[NUM];
int[] randInt =new int[NUM];
int sum=0;
for(int i=0;i<NUM;i++){
randInt[i]=1+(int)(Math.random()*10);
sum+=randInt[i];
}
DecimalFormat dF=new DecimalFormat(".00");
float sumprop=0;
for(int i=0;i<NUM;i++){
prop[i]= Float.parseFloat(dF.format(1.0*randInt[i]/sum));
sumprop+=prop[i];
}
sumprop=Float.parseFloat(dF.format(sumprop));
if(sumprop<1){
prop[NUM-1]+=1-sumprop;
}
else {
prop[NUM - 1] -= sumprop - 1;
}
return prop;

}

}
原文地址:https://www.cnblogs.com/ffaiss/p/11663601.html