線性同余法隨機數生成器


 

線性同余法隨機數生成器

/**
 * 線性同余法.  rand[n + 1] = (a * rand[n] + b) % length
 */
public class RandomNumber {
    private static final int a = 1664525;
    private static final int b = 1013904223;
    private static final int m = 0x7FFF_FFFF;
    private final int length;
    private int rand;

    public RandomNumber(int seed, int length) {
        this.rand = seed * (this.length = length);
    }

    private int rand() {
        return (this.rand = a * rand + b & m);// 先計算乘法, 再計算加法, 然后計算按位與
    }

    public int next() {
        return rand() % length;
    }

    public int next0or1() {
        return next() < (length / 2) ? 0 : 1;
    }

    public List<Integer> getMany(int many) {
        return new ArrayList<Integer>(many) {{
            for (int i = 0; i < many; i++) add(next());
        }};
    }

    public static void main(String[] args) {
        RandomNumber rr = new RandomNumber(333, 100);
        // 輸出 10 個100以內的隨機數.
        for (int i = 0; i < 10; i++) {
            System.out.println(rr.next());
        }

        System.out.println("****************************");

        // 輸出10個0 或者 1. 相當於拋硬幣.
        for (int i = 0; i < 10; i++) {
            System.out.println(rr.next0or1());
        }
    }
}

 

參考: https://www.cnblogs.com/xkfz007/archive/2012/03/27/2420154.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM