对于您上面给出的具体问题,其他人提供的解决方案效果很好,而别名方法将是矫枉过正。但是,您在评论中说您实际上打算在范围更大的发行版中使用它。在这种情况下,设置别名表的开销可能值得获得 O(1) 行为以实际生成值。
这是Java中的源代码。Random
如果您不想使用 Mersenne Twister ,很容易将其恢复为使用 Java 的股票:
/*
* Created on Mar 12, 2007
* Feb 13, 2011: Updated to use Mersenne Twister - pjs
*/
package edu.nps.or.simutils;
import java.lang.IllegalArgumentException;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.Stack;
import java.util.PriorityQueue;
import java.util.Random;
import net.goui.util.MTRandom;
public class AliasTable<V> {
private static Random r = new MTRandom();
private static DecimalFormat df2 = new DecimalFormat(" 0.00;-0.00");
private V[] primary;
private V[] alias;
private double[] primaryP;
private double[] primaryPgivenCol;
private static boolean notCloseEnough(double target, double value) {
return Math.abs(target - value) > 1E-10;
}
/**
* Constructs the AliasTable given the set of values
* and corresponding probabilities.
* @param value
* An array of the set of outcome values for the distribution.
* @param pOfValue
* An array of corresponding probabilities for each outcome.
* @throws IllegalArgumentException
* The values and probability arrays must be of the same length,
* the probabilities must all be positive, and they must sum to one.
*/
public AliasTable(V[] value, double[] pOfValue) {
super();
if (value.length != pOfValue.length) {
throw new IllegalArgumentException(
"Args to AliasTable must be vectors of the same length.");
}
double total = 0.0;
for (double d : pOfValue) {
if (d < 0) {
throw new
IllegalArgumentException("p_values must all be positive.");
}
total += d;
}
if (notCloseEnough(1.0, total)) {
throw new IllegalArgumentException("p_values must sum to 1.0");
}
// Done with the safety checks, now let's do the work...
// Cloning the values prevents people from changing outcomes
// after the fact.
primary = value.clone();
alias = value.clone();
primaryP = pOfValue.clone();
primaryPgivenCol = new double[primary.length];
for (int i = 0; i < primaryPgivenCol.length; ++i) {
primaryPgivenCol[i] = 1.0;
}
double equiProb = 1.0 / primary.length;
/*
* Internal classes are UGLY!!!!
* We're what you call experts. Don't try this at home!
*/
class pComparator implements Comparator<Integer> {
public int compare(Integer i1, Integer i2) {
return primaryP[i1] < primaryP[i2] ? -1 : 1;
}
}
PriorityQueue<Integer> deficitSet =
new PriorityQueue<Integer>(primary.length, new pComparator());
Stack<Integer> surplusSet = new Stack<Integer>();
// initial allocation of values to deficit/surplus sets
for (int i = 0; i < primary.length; ++i) {
if (notCloseEnough(equiProb, primaryP[i])) {
if (primaryP[i] < equiProb) {
deficitSet.add(i);
} else {
surplusSet.add(i);
}
}
}
/*
* Pull the largest deficit element from what remains. Grab as
* much probability as you need from a surplus element. Re-allocate
* the surplus element based on the amount of probability taken from
* it to the deficit, surplus, or completed set.
*
* Lather, rinse, repeat.
*/
while (!deficitSet.isEmpty()) {
int deficitColumn = deficitSet.poll();
int surplusColumn = surplusSet.pop();
primaryPgivenCol[deficitColumn] = primaryP[deficitColumn] / equiProb;
alias[deficitColumn] = primary[surplusColumn];
primaryP[surplusColumn] -= equiProb - primaryP[deficitColumn];
if (notCloseEnough(equiProb, primaryP[surplusColumn])) {
if (primaryP[surplusColumn] < equiProb) {
deficitSet.add(surplusColumn);
} else {
surplusSet.add(surplusColumn);
}
}
}
}
/**
* Generate a value from the input distribution. The alias table
* does this in O(1) time, regardless of the number of elements in
* the distribution.
* @return
* A value from the specified distribution.
*/
public V generate() {
int column = (int) (primary.length * r.nextDouble());
return r.nextDouble() <= primaryPgivenCol[column] ?
primary[column] : alias[column];
}
public void printAliasTable() {
System.err.println("Primary\t\tprimaryPgivenCol\tAlias");
for(int i = 0; i < primary.length; ++i) {
System.err.println(primary[i] + "\t\t\t"
+ df2.format(primaryPgivenCol[i]) + "\t\t" + alias[i]);
}
System.err.println();
}
}