Skip to content

Commit

Permalink
自己实现的随机数生产器
Browse files Browse the repository at this point in the history
  • Loading branch information
floor07 committed Jan 28, 2017
1 parent f3496e8 commit b32d51b
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/main/java/chapter10/random/MyRandom.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package chapter10.random;


public class MyRandom {
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;
private int state;
public MyRandom(){
state=(int) (System.currentTimeMillis()%Integer.MAX_VALUE);
}

/**
* //防止移除的随机数 Xi+1=A(xi mod Q)-R[xi/Q]+Ms(xi)
* @return
*/
public int randomInt(){
int tmpState=A*(state%Q)-R*(state/Q);
if(tmpState>=0){
state=tmpState;
}else{
state=tmpState+M;
}
return state;
}
public double random0_1(){
return (double)randomInt()/M;
}
public static void main(String[] args) {
System.out.println(0xBL);
System.out.println(0x5DEECE66DL);
System.out.println((1L << 48) - 1);
//^ 异或
//>>> 无符号右移动
System.out.println((16l*0x5DEECE66DL+11)%((1L << 48) - 1));
System.out.println((16l*0x5DEECE66DL+11)&((1L << 48) - 1));
MyRandom rand=new MyRandom();
System.out.println(rand.randomInt());
}
}
56 changes: 56 additions & 0 deletions src/main/java/chapter10/random/MyRandom2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package chapter10.random;

import java.util.concurrent.atomic.AtomicLong;

/**
* 仿Java实现 Xi+1=(multiplier*Xi+addend)%mask
* multiplier=25214903917
* addend=11
* mask=2^48-1
* nextInt截取前32位
* @author wenl
*/
public class MyRandom2 {

private static final Long multiplier=25214903917l;
private static final long addend = 11l;
private static final long mask = (1L << 48) - 1;
private AtomicLong seed;//保证线程安全
public MyRandom2(){
this.seed = new AtomicLong((8682522807148012L*181783497276652981L )^System.nanoTime());
}

public int nextInt() {
return next(32);
}
private int next(int bits) {
long oldseed, nextseed;
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) % mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}

/**
* 26与27和53的选择,基于实际经验,这样会产生最后的随机数
* @return
*/
public double next0_1() {
return (((long)(next(26)) << 27) + next(27))
/ (double)(1L << 53);
}

public static void main(String[] args) {
System.out.println(0xBL);
System.out.println(0x5DEECE66DL);
System.out.println((1L << 48) - 1);
//^ 异或
//>>> 无符号右移动
System.out.println((16l*0x5DEECE66DL+11)%((1L << 48) - 1));
System.out.println((16l*0x5DEECE66DL+11)&((1L << 48) - 1));
MyRandom2 rand=new MyRandom2();
System.out.println(rand.nextInt());
}
}

0 comments on commit b32d51b

Please sign in to comment.