Java实现高效随机数算法的示例代码---梅森旋转算法(Mersenne twister)

简介: Java实现高效随机数算法的示例代码梅森旋转算法(Mersenne twister)是一个伪随机数发生算法。由松本真和西村拓士在1997年开发,基于有限二进制字段上的矩阵线性递归。可以快速产生高质量的伪随机数,修正了古典随机数发生算法的很多缺陷。最为广泛使用Mersenne Twister的一种变体是MT19937,可以产生32位整数序列。
import java.util.Random;

/**
 * MT19937的Java实现
 */
public class MTRandom extends Random {
  
  // Constants used in the original C implementation
  private final static int UPPER_MASK = 0x80000000;
  private final static int LOWER_MASK = 0x7fffffff;

  private final static int N = 624;
  private final static int M = 397;
  private final static int MAGIC[] = { 0x0, 0x9908b0df };
  private final static int MAGIC_FACTOR1 = 1812433253;
  private final static int MAGIC_FACTOR2 = 1664525;
  private final static int MAGIC_FACTOR3 = 1566083941;
  private final static int MAGIC_MASK1  = 0x9d2c5680;
  private final static int MAGIC_MASK2  = 0xefc60000;
  private final static int MAGIC_SEED  = 19650218;
  private final static long DEFAULT_SEED = 5489L;

  // Internal state
  private transient int[] mt;
  private transient int mti;
  private transient boolean compat = false;

  // Temporary buffer used during setSeed(long)
  private transient int[] ibuf;

  /**
   * The default constructor for an instance of MTRandom. This invokes
   * the no-argument constructor for java.util.Random which will result
   * in the class being initialised with a seed value obtained by calling
   * System.currentTimeMillis().
   */
  public MTRandom() { }

  /**
   * This version of the constructor can be used to implement identical
   * behaviour to the original C code version of this algorithm including
   * exactly replicating the case where the seed value had not been set
   * prior to calling genrand_int32.
   * <p>
   * If the compatibility flag is set to true, then the algorithm will be
   * seeded with the same default value as was used in the original C
   * code. Furthermore the setSeed() method, which must take a 64 bit
   * long value, will be limited to using only the lower 32 bits of the
   * seed to facilitate seamless migration of existing C code into Java
   * where identical behaviour is required.
   * <p>
   * Whilst useful for ensuring backwards compatibility, it is advised
   * that this feature not be used unless specifically required, due to
   * the reduction in strength of the seed value.
   *
   * @param compatible Compatibility flag for replicating original
   * behaviour.
   */
  public MTRandom(boolean compatible) {
    super(0L);
    compat = compatible;
    setSeed(compat?DEFAULT_SEED:System.currentTimeMillis());
  }

  /**
   * This version of the constructor simply initialises the class with
   * the given 64 bit seed value. For a better random number sequence
   * this seed value should contain as much entropy as possible.
   *
   * @param seed The seed value with which to initialise this class.
   */
  public MTRandom(long seed) {
    super(seed);
  }

  /**
   * This version of the constructor initialises the class with the
   * given byte array. All the data will be used to initialise this
   * instance.
   *
   * @param buf The non-empty byte array of seed information.
   * @throws NullPointerException if the buffer is null.
   * @throws IllegalArgumentException if the buffer has zero length.
   */
  public MTRandom(byte[] buf) {
    super(0L);
    setSeed(buf);
  }

  /**
   * This version of the constructor initialises the class with the
   * given integer array. All the data will be used to initialise
   * this instance.
   *
   * @param buf The non-empty integer array of seed information.
   * @throws NullPointerException if the buffer is null.
   * @throws IllegalArgumentException if the buffer has zero length.
   */
  public MTRandom(int[] buf) {
    super(0L);
    setSeed(buf);
  }

  // Initializes mt[N] with a simple integer seed. This method is
  // required as part of the Mersenne Twister algorithm but need
  // not be made public.
  private final void setSeed(int seed) {

    // Annoying runtime check for initialisation of internal data
    // caused by java.util.Random invoking setSeed() during init.
    // This is unavoidable because no fields in our instance will
    // have been initialised at this point, not even if the code
    // were placed at the declaration of the member variable.
    if (mt == null) mt = new int[N];

    // ---- Begin Mersenne Twister Algorithm ----
    mt[0] = seed;
    for (mti = 1; mti < N; mti++) {
      mt[mti] = (MAGIC_FACTOR1 * (mt[mti-1] ^ (mt[mti-1] >>> 30)) + mti);
    }
    // ---- End Mersenne Twister Algorithm ----
  }

  /**
   * This method resets the state of this instance using the 64
   * bits of seed data provided. Note that if the same seed data
   * is passed to two different instances of MTRandom (both of
   * which share the same compatibility state) then the sequence
   * of numbers generated by both instances will be identical.
   * <p>
   * If this instance was initialised in 'compatibility' mode then
   * this method will only use the lower 32 bits of any seed value
   * passed in and will match the behaviour of the original C code
   * exactly with respect to state initialisation.
   *
   * @param seed The 64 bit value used to initialise the random
   * number generator state.
   */
  public final synchronized void setSeed(long seed) {
    if (compat) {
      setSeed((int)seed);
    } else {

      // Annoying runtime check for initialisation of internal data
      // caused by java.util.Random invoking setSeed() during init.
      // This is unavoidable because no fields in our instance will
      // have been initialised at this point, not even if the code
      // were placed at the declaration of the member variable.
      if (ibuf == null) ibuf = new int[2];

      ibuf[0] = (int)seed;
      ibuf[1] = (int)(seed >>> 32);
      setSeed(ibuf);
    }
  }

  /**
   * This method resets the state of this instance using the byte
   * array of seed data provided. Note that calling this method
   * is equivalent to calling "setSeed(pack(buf))" and in particular
   * will result in a new integer array being generated during the
   * call. If you wish to retain this seed data to allow the pseudo
   * random sequence to be restarted then it would be more efficient
   * to use the "pack()" method to convert it into an integer array
   * first and then use that to re-seed the instance. The behaviour
   * of the class will be the same in both cases but it will be more
   * efficient.
   *
   * @param buf The non-empty byte array of seed information.
   * @throws NullPointerException if the buffer is null.
   * @throws IllegalArgumentException if the buffer has zero length.
   */
  public final void setSeed(byte[] buf) {
    setSeed(pack(buf));
  }

  /**
   * This method resets the state of this instance using the integer
   * array of seed data provided. This is the canonical way of
   * resetting the pseudo random number sequence.
   *
   * @param buf The non-empty integer array of seed information.
   * @throws NullPointerException if the buffer is null.
   * @throws IllegalArgumentException if the buffer has zero length.
   */
  public final synchronized void setSeed(int[] buf) {
    int length = buf.length;
    if (length == 0) throw new IllegalArgumentException("Seed buffer may not be empty");
    // ---- Begin Mersenne Twister Algorithm ----
    int i = 1, j = 0, k = (N > length ? N : length);
    setSeed(MAGIC_SEED);
    for (; k > 0; k--) {
      mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR2)) + buf[j] + j;
      i++; j++;
      if (i >= N) { mt[0] = mt[N-1]; i = 1; }
      if (j >= length) j = 0;
    }
    for (k = N-1; k > 0; k--) {
      mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >>> 30)) * MAGIC_FACTOR3)) - i;
      i++;
      if (i >= N) { mt[0] = mt[N-1]; i = 1; }
    }
    mt[0] = UPPER_MASK; // MSB is 1; assuring non-zero initial array
    // ---- End Mersenne Twister Algorithm ----
  }

  /**
   * This method forms the basis for generating a pseudo random number
   * sequence from this class. If given a value of 32, this method
   * behaves identically to the genrand_int32 function in the original
   * C code and ensures that using the standard nextInt() function
   * (inherited from Random) we are able to replicate behaviour exactly.
   * <p>
   * Note that where the number of bits requested is not equal to 32
   * then bits will simply be masked out from the top of the returned
   * integer value. That is to say that:
   * <pre>
   * mt.setSeed(12345);
   * int foo = mt.nextInt(16) + (mt.nextInt(16) << 16);</pre>
   * will not give the same result as
   * <pre>
   * mt.setSeed(12345);
   * int foo = mt.nextInt(32);</pre>
   *
   * @param bits The number of significant bits desired in the output.
   * @return The next value in the pseudo random sequence with the
   * specified number of bits in the lower part of the integer.
   */
  protected final synchronized int next(int bits) {
    // ---- Begin Mersenne Twister Algorithm ----
    int y, kk;
    if (mti >= N) {       // generate N words at one time

      // In the original C implementation, mti is checked here
      // to determine if initialisation has occurred; if not
      // it initialises this instance with DEFAULT_SEED (5489).
      // This is no longer necessary as initialisation of the
      // Java instance must result in initialisation occurring
      // Use the constructor MTRandom(true) to enable backwards
      // compatible behaviour.

      for (kk = 0; kk < N-M; kk++) {
        y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
        mt[kk] = mt[kk+M] ^ (y >>> 1) ^ MAGIC[y & 0x1];
      }
      for (;kk < N-1; kk++) {
        y = (mt[kk] & UPPER_MASK) | (mt[kk+1] & LOWER_MASK);
        mt[kk] = mt[kk+(M-N)] ^ (y >>> 1) ^ MAGIC[y & 0x1];
      }
      y = (mt[N-1] & UPPER_MASK) | (mt[0] & LOWER_MASK);
      mt[N-1] = mt[M-1] ^ (y >>> 1) ^ MAGIC[y & 0x1];

      mti = 0;
    }

    y = mt[mti++];

    // Tempering
    y ^= (y >>> 11);
    y ^= (y << 7) & MAGIC_MASK1;
    y ^= (y << 15) & MAGIC_MASK2;
    y ^= (y >>> 18);
    // ---- End Mersenne Twister Algorithm ----
    return (y >>> (32-bits));
  }

  // This is a fairly obscure little code section to pack a
  // byte[] into an int[] in little endian ordering.

  /**
   * This simply utility method can be used in cases where a byte
   * array of seed data is to be used to repeatedly re-seed the
   * random number sequence. By packing the byte array into an
   * integer array first, using this method, and then invoking
   * setSeed() with that; it removes the need to re-pack the byte
   * array each time setSeed() is called.
   * <p>
   * If the length of the byte array is not a multiple of 4 then
   * it is implicitly padded with zeros as necessary. For example:
   * <pre>  byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 }</pre>
   * becomes
   * <pre>  int[] { 0x04030201, 0x00000605 }</pre>
   * <p>
   * Note that this method will not complain if the given byte array
   * is empty and will produce an empty integer array, but the
   * setSeed() method will throw an exception if the empty integer
   * array is passed to it.
   *
   * @param buf The non-null byte array to be packed.
   * @return A non-null integer array of the packed bytes.
   * @throws NullPointerException if the given byte array is null.
   */
  public static int[] pack(byte[] buf) {
    int k, blen = buf.length, ilen = ((buf.length+3) >>> 2);
    int[] ibuf = new int[ilen];
    for (int n = 0; n < ilen; n++) {
      int m = (n+1) << 2;
      if (m > blen) m = blen;
      for (k = buf[--m]&0xff; (m & 0x3) != 0; k = (k << 8) | buf[--m]&0xff);
      ibuf[n] = k;
    }
    return ibuf;
  }
}
目录
相关文章
|
8月前
|
设计模式 算法 搜索推荐
Java 设计模式之策略模式:灵活切换算法的艺术
策略模式通过封装不同算法并实现灵活切换,将算法与使用解耦。以支付为例,微信、支付宝等支付方式作为独立策略,购物车根据选择调用对应支付逻辑,提升代码可维护性与扩展性,避免冗长条件判断,符合开闭原则。
2228 35
|
8月前
|
存储 人工智能 算法
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
在算法世界里,有一种思想如同生活中的"见好就收"——每次做出当前看来最优的选择,寄希望于通过局部最优达成全局最优。这种思想就是贪心算法,它以其简洁高效的特点,成为解决最优问题的利器。今天我们就来系统学习贪心算法的核心思想,并通过10道LeetCode经典题目实战演练,带你掌握这种"步步为营"的解题思维。
|
8月前
|
存储 算法 搜索推荐
《数据之美》:Java数据结构与算法精要
本系列深入探讨数据结构与算法的核心原理及Java实现,涵盖线性与非线性结构、常用算法分类、复杂度分析及集合框架应用,助你提升程序效率,掌握编程底层逻辑。
|
10月前
|
运维 监控 算法
基于 Java 滑动窗口算法的局域网内部监控软件流量异常检测技术研究
本文探讨了滑动窗口算法在局域网流量监控中的应用,分析其在实时性、资源控制和多维分析等方面的优势,并提出优化策略,结合Java编程实现高效流量异常检测。
412 0
|
11月前
|
机器学习/深度学习 算法 Java
Java实现林火蔓延路径算法
记录正在进行的森林防火项目中林火蔓延功能,本篇文章可以较好的实现森林防火蔓延,但还存在很多不足,如:很多参数只能使用默认值,所以蔓延范围仅供参考。(如果底层设备获取的数据充足,那当我没说)。注:因林火蔓延涉及因素太多,如静可燃物载量、矿质阻尼系数等存在估值,所以得出的结果仅供参考。
506 5
|
11月前
|
存储 监控 算法
企业上网监控场景下布隆过滤器的 Java 算法构建及其性能优化研究
布隆过滤器是一种高效的数据结构,广泛应用于企业上网监控系统中,用于快速判断员工访问的网址是否为违规站点。相比传统哈希表,它具有更低的内存占用和更快的查询速度,支持实时拦截、动态更新和资源压缩,有效提升系统性能并降低成本。
513 0
|
11月前
|
存储 负载均衡 算法
我们来说一说 Java 的一致性 Hash 算法
我是小假 期待与你的下一次相遇 ~
608 1
|
存储 算法 安全
Java中的对称加密算法的原理与实现
本文详细解析了Java中三种常用对称加密算法(AES、DES、3DES)的实现原理及应用。对称加密使用相同密钥进行加解密,适合数据安全传输与存储。AES作为现代标准,支持128/192/256位密钥,安全性高;DES采用56位密钥,现已不够安全;3DES通过三重加密增强安全性,但性能较低。文章提供了各算法的具体Java代码示例,便于快速上手实现加密解密操作,帮助用户根据需求选择合适的加密方案保护数据安全。
849 58
|
人工智能 算法 NoSQL
LRU算法的Java实现
LRU(Least Recently Used)算法用于淘汰最近最少使用的数据,常应用于内存管理策略中。在Redis中,通过`maxmemory-policy`配置实现不同淘汰策略,如`allkeys-lru`和`volatile-lru`等,采用采样方式近似LRU以优化性能。Java中可通过`LinkedHashMap`轻松实现LRUCache,利用其`accessOrder`特性和`removeEldestEntry`方法完成缓存淘汰逻辑,代码简洁高效。
583 0

热门文章

最新文章