标签:
public class Random { private static final int A=48271; private static final int M=2147483647; private static final int Q=M/A; private static final int R=M%A; public Random() { this((int)(System.currentTimeMillis()%Integer.MAX_VALUE)); } /*CONSTRUCT this b Random object with specified inital state * */ public Random(int initialValue) { if(initialValue<0) initialValue+=M; state=initialValue; if(state==0) state=1; } public int nextInt() { int tmpState=A*(state%Q)-R*(state/Q); if(tmpState>=0) state=tmpState; else state=tmpState+M; return state; } public int nextIntWRONG( ) { return state = ( A * state ) % M; } public double nextDouble() { return (double)nextInt( )/ M; } public long nextLong( ) { return ( (long) nextInt( ) << 31 ) + nextInt( ); } public int nextInt(int low,int high) { double partitionSize = (double) M / ( high - low + 1 ); return (int) ( nextInt( ) / partitionSize ) + low; } public int nextPoissson(double excepctedValue) //服从泊松分布的随机数的产生 { double limit=-excepctedValue; double product =Math.log(nextDouble()); int count; for(count=0;product>limit;count++) product+=Math.log(nextDouble()); return count; } public double nextNegExp(double exceptedValue) //服从负指数分布的随机数的产生,负指数=分布具有相同的均值和方差,用于刻画随机事件发生的时间间隔 { return -exceptedValue*Math.log(nextDouble()); } public static final <AnyType> void permute( AnyType [ ] a ) { Random r = new Random( ); for( int j = 1; j < a.length; j++ ) swapReferences( a, j, r.nextInt( 0, j ) ); } private static final <AnyType> void swapReferences( AnyType [ ] a, int index1, int index2 ) { AnyType tmp = a[ index1 ]; a[ index1 ] = a[ index2 ]; a[ index2 ] = tmp; } private int state; // Test program public static void main( String [ ] args ) { Random r = new Random( ); for( int i = 0; i < 20; i++ ) System.out.println( r.nextInt( ) ); int [ ] dist = new int[ 10000 ]; final int SAMPLES = 1000000; for( int i = 0; i < SAMPLES; i++ ) dist[ r.nextPoissson( 2 ) ]++; for( int i = 0; i < 10; i++ ) System.out.println( i + ": " + dist[ i ] / (double) SAMPLES ); } }
标签:
原文地址:http://www.cnblogs.com/fanerna/p/5410682.html