java随机数生成具体实现代码

本文实例为大家分享了java随机数生成代码,供大家参考,具体内容如下

package com.gonvan.common.utils;

import java.util.*;

/**
 * 随机数工具
 *
 * @author yuerzm
 *
 */
public final class LotteryAliasMethod {

  /**
   * The random number generator used to sample from the distribution.
   */
  private final Random  random;

  /**
   * The alias tables.
   */
  private final int[]   alias;

  /**
   * The probability tables.
   */
  private final double[] probability;

  /**
   * Constructs a new AliasMethod to sample from a discrete distribution and
   * hand back outcomes based on the probability distribution.
   * <p/>
   * Given as input a list of probabilities corresponding to outcomes 0, 1,
   * ..., n - 1, this constructor creates the probability and alias tables
   * needed to efficiently sample from this distribution.
   *
   * @param probabilities
   *      The list of probabilities.
   */
  public LotteryAliasMethod(List<Double> probabilities) {
    this(probabilities, new Random());
  }

  /**
   * Constructs a new AliasMethod to sample from a discrete distribution and
   * hand back outcomes based on the probability distribution.
   * <p/>
   * Given as input a list of probabilities corresponding to outcomes 0, 1,
   * ..., n - 1, along with the random number generator that should be used as
   * the underlying generator, this constructor creates the probability and
   * alias tables needed to efficiently sample from this distribution.
   *
   * @param probabilities
   *      The list of probabilities.
   * @param random
   *      The random number generator
   */
  public LotteryAliasMethod(List<Double> probabilities, Random random) {
    /* Begin by doing basic structural checks on the inputs. */
    if (probabilities == null || random == null)
      throw new NullPointerException();
    if (probabilities.size() == 0)
      throw new IllegalArgumentException("Probability vector must be nonempty.");

    /* Allocate space for the probability and alias tables. */
    probability = new double[probabilities.size()];
    alias = new int[probabilities.size()];

    /* Store the underlying generator. */
    this.random = random;

    /* Compute the average probability and cache it for later use. */
    final double average = 1.0 / probabilities.size();

    /*
     * Make a copy of the probabilities list, since we will be making
     * changes to it.
     */
    probabilities = new ArrayList<Double>(probabilities);

    /* Create two stacks to act as worklists as we populate the tables. */
    Deque<Integer> small = new ArrayDeque<Integer>();
    Deque<Integer> large = new ArrayDeque<Integer>();

    /* Populate the stacks with the input probabilities. */
    for (int i = 0; i < probabilities.size(); ++i) {
      /*
       * If the probability is below the average probability, then we add
       * it to the small list; otherwise we add it to the large list.
       */
      if (probabilities.get(i) >= average)
        large.add(i);
      else
        small.add(i);
    }

    /*
     * As a note: in the mathematical specification of the algorithm, we
     * will always exhaust the small list before the big list. However,
     * due to floating point inaccuracies, this is not necessarily true.
     * Consequently, this inner loop (which tries to pair small and large
     * elements) will have to check that both lists aren't empty.
     */
    while (!small.isEmpty() && !large.isEmpty()) {
      /* Get the index of the small and the large probabilities. */
      int less = small.removeLast();
      int more = large.removeLast();

      /*
       * These probabilities have not yet been scaled up to be such that
       * 1/n is given weight 1.0. We do this here instead.
       */
      probability[less] = probabilities.get(less) * probabilities.size();
      alias[less] = more;

      /*
       * Decrease the probability of the larger one by the appropriate
       * amount.
       */
      probabilities.set(more, (probabilities.get(more) + probabilities.get(less)) - average);

      /*
       * If the new probability is less than the average, add it into the
       * small list; otherwise add it to the large list.
       */
      if (probabilities.get(more) >= 1.0 / probabilities.size())
        large.add(more);
      else
        small.add(more);
    }

    /*
     * At this point, everything is in one list, which means that the
     * remaining probabilities should all be 1/n. Based on this, set them
     * appropriately. Due to numerical issues, we can't be sure which
     * stack will hold the entries, so we empty both.
     */
    while (!small.isEmpty())
      probability[small.removeLast()] = 1.0;
    while (!large.isEmpty())
      probability[large.removeLast()] = 1.0;
  }

  /**
   * Samples a value from the underlying distribution.
   *
   * @return A random value sampled from the underlying distribution.
   */
  public int next() {
    /* Generate a fair die roll to determine which column to inspect. */
    int column = random.nextInt(probability.length);

    /* Generate a biased coin toss to determine which option to pick. */
    boolean coinToss = random.nextDouble() < probability[column];

    /* Based on the outcome, return either the column or its alias. */
    return coinToss ? column : alias[column];
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助。

(0)

相关推荐

  • Java编程中随机数的生成方式总结

    本章先讲解Java随机数的几种产生方式,然后通过示例对其进行演示. 广义上讲,Java中的随机数的有三种产生方式: (01). 通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字. (02). 通过Math.random()返回一个0到1之间的double值. (03). 通过Random类来产生一个随机数,这个是专业的Random工具类,功能强大.第1种 利用System.currentTimeMillis()获取随机数 通过System.curr

  • Java实现按权重随机数

    一.问题定义: 问下有一个数组,这些数组中的值都有自己的权重,怎样设计才能高效的优先取出权重高的数?? 例如: 复制代码 代码如下: 权重: 8  2  11  79 权重返回的值: 0  1  2   3 二.分析问题: 思路一:创建一个数组数组大小为权重和的大小,如值0的权重是8,则放入8个0值,值1的权重是2,则放入2个1值,依次类推. 然后用用一个权重和大小的随机数,产生随机数,即可.缺点要占用过多的内存. 思路二: 权重和数组 w[i]存储的是[0,i]元素的所有元素的权重和  时间复

  • 浅谈Java中随机数的几种实现方式

    众所周知,随机数是任何一种编程语言最基本的特征之一.而生成随机数的基本方式也是相同的:产生一个0到1之间的随机数.看似简单,但有时我们也会忽略了一些有趣的功能. 我们从书本上学到什么? 最明显的,也是直观的方式,在Java中生成随机数只要简单的调用: java.lang.Math.random() 在所有其他语言中,生成随机数就像是使用Math工具类,如abs, pow, floor, sqrt和其他数学函数.大多数人通过书籍.教程和课程来了解这个类.一个简单的例子:从0.0到1.0之间可以生成

  • 浅谈Java中的n种随机数产生办法

    我们从书本上学到什么? 最明显的,也是直观的方式,在Java中生成随机数只要简单的调用: java.lang.Math.random() 在所有其他语言中,生成随机数就像是使用Math工具类,如abs, pow, floor, sqrt和其他数学函数.大多数人通过书籍.教程和课程来了解这个类.一个简单的例子:从0.0到1.0之间可以生成一个双精度浮点数.那么通过上面的信息,开发人员要产生0.0和10.0之间的双精度浮点数会这样来写: Math.random() * 10 而产生0和10之间的整数

  • Java获取随机数的3种方法

    主要介绍了Java获取随机数的3种方法,主要利用random()函数来实现 方法1 (数据类型)(最小值+Math.random()*(最大值-最小值+1))例: (int)(1+Math.random()*(10-1+1)) 从1到10的int型随数 方法2 获得随机数 for (int i=0;i<30;i++) {System.out.println((int)(1+Math.random()*10));} (int)(1+Math.random()*10) 通过java.Math包的ra

  • Java中生成随机数的实现方法总结

    在实际开发工作中经常需要用到随机数.如有些系统中创建用户后会给用户一个随机的初始化密码.这个密码由于是随机的,为此往往只有用户自己知道.他们获取了这个随机密码之后,需要马上去系统中更改.这就是利用随机数的原理.总之随机数在日常开发工作中经常用到.而不同的开发语言产生随机数的方法以及技巧各不相同.笔者这里就以Java语言为例,谈谈随机数生成的方法以及一些技巧. 一.利用random方法来生成随机数. 在Java语言中生成随机数相对来说比较简单,因为有一个现成的方法可以使用.在Math类中,Java

  • Java生成10个1000以内的随机数并用消息框显示数组内容然后求和输出

    本文最终结果大概是这样的,使用java技术随机生成10个数,然后填充一个数组并在消息框中显示数组内容,接着对数组求和输出,将结果显示在消息框中. 设计思路:可以先用Math.Random()*1000生成1000以内随机数,然后依次存入数组中,然后读取数组,输出随机数,同时进行加法计算,最后将所有结果以消息框形式输出. 程序流程图: 源代码: package 随机数求和; import javax.swing.*; public class Sum { public static void ma

  • Java生产1-100的随机数简单实例(分享)

    直接调用Math里面的random即可,简单方便 int i = (int)(Math.random()*100+1); 以上这篇Java生产1-100的随机数简单实例(分享)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们.

  • java生成抽样随机数的多种算法

    本章先讲解Java随机数的几种产生方式,然后通过示例对其进行演示. 概述: 这里你是不是会说,生成随机数有什么难的?不就是直接使用Java封装好了的random就行了么?当然对于一般情况下是OK的,而且本文要说明的这些算法也是基于这个random库函数的. 本文主要是针对抽样这一行为进行的,而抽样本身有一个隐含的规则就是不要有重复数据.好了,有了这些说明.你可以先尝试着用一些自己的想法来实现不重复地生成随机数. 算法尝试: 一些好的算法出现,往往伴随着一些不那么好的算法.但是对于效果不太好的算法

  • Java生成随机数的方法

    1.通过System.currentTimeMillis()来获取一个当前时间毫秒数的long型数字. long a = System.currentTimeMillis(); System.out.println(a); 2.通过Math.random()返回一个0到1之间的double值. int b = (int)(Math.random()*99+1); System.out.println(b); 3.通过Random类来产生一个随机数. Random random = new Ran

随机推荐