java随机数生成具体实现代码
本文实例为大家分享了java随机数生成代码,供大家参考,具体内容如下
packagecom.gonvan.common.utils;
importjava.util.*;
/**
*随机数工具
*
*@authoryuerzm
*
*/
publicfinalclassLotteryAliasMethod{
/**
*Therandomnumbergeneratorusedtosamplefromthedistribution.
*/
privatefinalRandomrandom;
/**
*Thealiastables.
*/
privatefinalint[]alias;
/**
*Theprobabilitytables.
*/
privatefinaldouble[]probability;
/**
*ConstructsanewAliasMethodtosamplefromadiscretedistributionand
*handbackoutcomesbasedontheprobabilitydistribution.
*<p/>
*Givenasinputalistofprobabilitiescorrespondingtooutcomes0,1,
*...,n-1,thisconstructorcreatestheprobabilityandaliastables
*neededtoefficientlysamplefromthisdistribution.
*
*@paramprobabilities
*Thelistofprobabilities.
*/
publicLotteryAliasMethod(List<Double>probabilities){
this(probabilities,newRandom());
}
/**
*ConstructsanewAliasMethodtosamplefromadiscretedistributionand
*handbackoutcomesbasedontheprobabilitydistribution.
*<p/>
*Givenasinputalistofprobabilitiescorrespondingtooutcomes0,1,
*...,n-1,alongwiththerandomnumbergeneratorthatshouldbeusedas
*theunderlyinggenerator,thisconstructorcreatestheprobabilityand
*aliastablesneededtoefficientlysamplefromthisdistribution.
*
*@paramprobabilities
*Thelistofprobabilities.
*@paramrandom
*Therandomnumbergenerator
*/
publicLotteryAliasMethod(List<Double>probabilities,Randomrandom){
/*Beginbydoingbasicstructuralchecksontheinputs.*/
if(probabilities==null||random==null)
thrownewNullPointerException();
if(probabilities.size()==0)
thrownewIllegalArgumentException("Probabilityvectormustbenonempty.");
/*Allocatespacefortheprobabilityandaliastables.*/
probability=newdouble[probabilities.size()];
alias=newint[probabilities.size()];
/*Storetheunderlyinggenerator.*/
this.random=random;
/*Computetheaverageprobabilityandcacheitforlateruse.*/
finaldoubleaverage=1.0/probabilities.size();
/*
*Makeacopyoftheprobabilitieslist,sincewewillbemaking
*changestoit.
*/
probabilities=newArrayList<Double>(probabilities);
/*Createtwostackstoactasworklistsaswepopulatethetables.*/
Deque<Integer>small=newArrayDeque<Integer>();
Deque<Integer>large=newArrayDeque<Integer>();
/*Populatethestackswiththeinputprobabilities.*/
for(inti=0;i<probabilities.size();++i){
/*
*Iftheprobabilityisbelowtheaverageprobability,thenweadd
*ittothesmalllist;otherwiseweaddittothelargelist.
*/
if(probabilities.get(i)>=average)
large.add(i);
else
small.add(i);
}
/*
*Asanote:inthemathematicalspecificationofthealgorithm,we
*willalwaysexhaustthesmalllistbeforethebiglist.However,
*duetofloatingpointinaccuracies,thisisnotnecessarilytrue.
*Consequently,thisinnerloop(whichtriestopairsmallandlarge
*elements)willhavetocheckthatbothlistsaren'tempty.
*/
while(!small.isEmpty()&&!large.isEmpty()){
/*Gettheindexofthesmallandthelargeprobabilities.*/
intless=small.removeLast();
intmore=large.removeLast();
/*
*Theseprobabilitieshavenotyetbeenscaleduptobesuchthat
*1/nisgivenweight1.0.Wedothishereinstead.
*/
probability[less]=probabilities.get(less)*probabilities.size();
alias[less]=more;
/*
*Decreasetheprobabilityofthelargeronebytheappropriate
*amount.
*/
probabilities.set(more,(probabilities.get(more)+probabilities.get(less))-average);
/*
*Ifthenewprobabilityislessthantheaverage,additintothe
*smalllist;otherwiseaddittothelargelist.
*/
if(probabilities.get(more)>=1.0/probabilities.size())
large.add(more);
else
small.add(more);
}
/*
*Atthispoint,everythingisinonelist,whichmeansthatthe
*remainingprobabilitiesshouldallbe1/n.Basedonthis,setthem
*appropriately.Duetonumericalissues,wecan'tbesurewhich
*stackwillholdtheentries,soweemptyboth.
*/
while(!small.isEmpty())
probability[small.removeLast()]=1.0;
while(!large.isEmpty())
probability[large.removeLast()]=1.0;
}
/**
*Samplesavaluefromtheunderlyingdistribution.
*
*@returnArandomvaluesampledfromtheunderlyingdistribution.
*/
publicintnext(){
/*Generateafairdierolltodeterminewhichcolumntoinspect.*/
intcolumn=random.nextInt(probability.length);
/*Generateabiasedcointosstodeterminewhichoptiontopick.*/
booleancoinToss=random.nextDouble()<probability[column];
/*Basedontheoutcome,returneitherthecolumnoritsalias.*/
returncoinToss?column:alias[column];
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助。