首页 > 代码库 > java:产生小数位数为2的随机概率,使得和为1

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

public static List<InstSec> setDataSec(List<String> instno) {		List<InstSec> result = new ArrayList<InstSec>();		String[] mon ={"2014-01","2014-02","2014-03","2014-04"};		int[] flag ={1,2,3,4,5};				List<String> instnosub5 = new ArrayList<String>();		for(int i=0;i<instno.size();i++){			if(!instnosub5.contains(instno.get(i).substring(0,5))){				instnosub5.add(instno.get(i).substring(0,5));			}		}				//对于每个organValue,每个月,都有五个等级,对应flag prop		for(int i=0;i<instnosub5.size();i++){			for(int j=0;j<mon.length;j++){				float[] prop = genProp();//注意:在此处产生随机概率				for(int k=0;k<flag.length;k++){					InstSec inst=new InstSec();					inst.setInst_no_sub5(instnosub5.get(i));					inst.setSa_tx_m(mon[j]);					inst.setFlag(flag[k]);					inst.setProp(prop[k]);					result.add(inst);				}			}		}		return result;	}		public static float[] genProp(){		//产生概率随机数,且让和为1		float[] prop =new float[5];		int[] randInt =new int[5];		int sum=0;		for(int i=0;i<5;i++){			randInt[i]=1+(int)(Math.random()*10);			sum+=randInt[i];		}
DecimalFormat dF=new DecimalFormat(".00"); float sumprop=0; for(int i=0;i<5;i++){ prop[i]= Float.parseFloat(dF.format(1.0*randInt[i]/sum));// System.out.println("prop is "+prop[i]); sumprop+=prop[i]; }// System.out.println("sumprop is "+sumprop); sumprop=Float.parseFloat(dF.format(sumprop)); if(sumprop<1) prop[4]+=1-sumprop; else prop[4]-=sumprop-1;// System.out.println("prop[4] is "+prop[4]); return prop; }

  注意:向SQL中传参数的下标是从1开始,java的substring方法从0开始

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