生成三维随机数空间的算法

时间:2011-07-05 16:45:53

标签: java algorithm math random

我正在寻找一种在大范围的三(或更好的)n维空间中生成伪随机数的算法。当用种子初始化时,生成器应该能够为同一种子重复产生相同的数字。

但与编程语言中可用的大多数生成器不同,它不应该仅返回序列中的下一个随机数,而是生成特定坐标的数字,无论请求值的顺序如何。

应该认为空间的大小太大而无法在初始化时生成所有数字。在Java中,它看起来像这样:

Random3D gen = new Random3D(seed);
int n1 = gen.getInt(3,0,6);
int n2 = gen.getInt(2,-3,1);
...

我该怎么做?

我在Java中尝试使用java.util.Random编写一些代码,但结果质量不是很好。

3 个答案:

答案 0 :(得分:5)

如果你想为同一个coordenate收到相同的结果,当你指定种子时,你就不会寻找真正的随机生成器。

你想要一个快速的算法,一个可靠的算法吗?对于快速的,请查看Mersenne twister。对于更强大的一个,你可以看Blum Blum Shub

您可以使用n维坐标和种子来生成伪随机数生成器。例如,您可以计算sha1或md5或坐标+种子的任何其他散列,并在PRNG中使用它。

编辑:对于一个简单的解决方案,math.random可以接收48位(小于md5输出)的种子,对于你的问题可能有点小(你提到有高维度,对吗?有大号)坐标?)

答案 1 :(得分:3)

我相信您可以通过将输入数字用作计算传递给标准RNG的种子的值来解决您的问题;如果我正确地读了你的问题,你想要从同一输入得到相同的“随机”数字,这个解决方案将提供。

答案 2 :(得分:2)

我实现了answer from woliveirajr给出的想法:使用Blum Blum Shub伪随机数生成器以其显式(非迭代)形式,以及消息摘要从参数生成正确的索引

(您也可以从my github repository获取此来源。)

package de.fencing_game.paul.examples;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;


/**
 * A pseudo random number generator, which does not
 * produce a series of numbers, but each number determined by
 * some input (and independent of earlier numbers).
 *<p>
 * This is based on the
 * <a href="http://en.wikipedia.org/wiki/Blum_Blum_Shub">Blum Blum Shub
 *  algorithm</a>, combined with the SHA-1 message digest to get the
 *  right index.
 *</p>
 *<p>
 * Inspired by the question
 *  <a href="https://stackoverflow.com/q/6586042/600500">Algorithm
 *   for generating a three dimensional random number space</a> on
 * Stack Overflow, and the answer from woliveirajr.
 */
public class PseudoRandom {

    /**
     * An instance of this class represents a range of
     * integer numbers, both endpoints inclusive.
     */
    public static final class Range {

        public int min;
        public int max;

        public Range(int min, int max) {
            this.min = min;
            this.max = max;
        }

        /**
         * clips a (positive) BigInteger to the range represented
         * by this object.
         * @returns an integer between min and max, inclusive.
         */
        final int clip(BigInteger bigVal) {
            BigInteger modulus =
                BigInteger.valueOf(max + 1L - min);
            return (int)(min + bigVal.mod(modulus).longValue());
        }
    }


    /* M = p * q =
       510458987753305598818664158496165644577818051165198667838943583049282929852810917684801057127 *
       1776854827630587786961501611493551956300146782768206322414884019587349631246969724030273647
     */
    /**
     * A big number, composed of two large primes.
     */
    private static final BigInteger M =
        new BigInteger("90701151669688414188903413878244126959941449657"+
                       "82009133495922185615411523457607691918744187485"+
                       "10492533485214517262505932675573506751182663319"+
                       "285975046876611245165890299147416689632169");

    /* λ(M) = lcm(p-1, q-1) */
    /**
     * The value of λ(M), where λ is the Carmichael function.
     * This is the lowest common multiple of the predecessors of
     * the two factors of M.
     */
    private static final BigInteger lambdaM =
        new BigInteger("53505758348442070944517069391220634799707248289"+
                       "10045667479610928077057617288038459593720911813"+
                       "73249762745139558184229125081884863164923576762"+
                       "05906844204771187443203120630003929150698");

    /**
     * The number 2 as a BigInteger, for use in the calculations.
     */
    private static final BigInteger TWO = BigInteger.valueOf(2);



    /**
     * the modular square of the seed value.
     */
    private BigInteger s_0;

    /**
     * The MessageDigest used to convert input data
     * to an index for our PRNG.
     */
    private MessageDigest md;



    /**
     * Creates a new PseudoRandom instance, using the given seed.
     */
    public PseudoRandom(BigInteger seed) {
        try {
            this.md = MessageDigest.getInstance("SHA-1");
        }
        catch(NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
        initializeSeed(seed);
    }

    /**
     * Creates a new PseudoRandom instance, seeded by the given seed.
     */
    public PseudoRandom(byte[] seed) {
        this(new BigInteger(1, seed));
    }

    /**
     * Creates a new PseudoRandom instance,
     * seeded by the current system time.
     */
    public PseudoRandom() {
        this(BigInteger.valueOf(System.currentTimeMillis()));
    }

    /**
     * Transforms the initial seed into some value that is
     * usable by the generator. (This is completely deterministic.)
     */
    private void initializeSeed(BigInteger proposal) {

        // we want our seed be big enough so s^2 > M.
        BigInteger s = proposal;
        while(s.bitLength() <= M.bitLength()/2) {
            s = s.shiftLeft(10);
        }
        // we want gcd(s, M) = 1
        while(!M.gcd(s).equals(BigInteger.ONE)) {
            s = s.add(BigInteger.ONE);
        }
        // we save s_0 = s^2 mod M
        this.s_0 = s.multiply(s).mod(M);
    }

    /**
     * calculates {@code x_k = r.clip( s_k )}.
     */
    private int calculate(Range r, BigInteger k) {
        BigInteger exp = TWO.modPow(k, lambdaM);
        BigInteger s_k = s_0.modPow(exp, M);
        return r.clip(s_k);
    }


    /**
     * returns a number given by a range, determined by the given input.
     */
    public int getNumber(Range r, byte[] input) {
        byte[] dig;
        synchronized(md) {
            md.reset();
            md.update(input);
            dig =  md.digest();
        }
        return calculate(r, new BigInteger(1, dig));
    }


    /**
     * returns a number given by a range, determined by the given input.
     */
    public int getNumber(Range r, int... input) {
        byte[] dig;
        synchronized(md) {
            md.reset();
            for(int i : input) {
                md.update(new byte[]{ (byte)(i >> 24), (byte)(i >> 16),
                                      (byte)(i >> 8), (byte)(i >> 0)} );
            }
            dig = md.digest();
        }
        return calculate(r, new BigInteger(1, dig));
    }

    /**
     * Test method.
     */
    public static void main(String[] test) {
        PseudoRandom pr = new PseudoRandom("Hallo Welt".getBytes());

        Range r = new Range(10, 30);
        for(int i = 0; i < 10; i++) {
            System.out.println("x("+i+") = " + pr.getNumber(r, i));
        }
        for(int i = 0; i < 5; i++) {
            for(int j = 0; j < 5; j++) {
                System.out.println("x("+i+", "+j+") = " +
                                   pr.getNumber(r, i, j));
            }
        }
        // to show that it really is deterministic:
        for(int i = 0; i < 10; i++) {
            System.out.println("x("+i+") = " + pr.getNumber(r, i));
        }
    }
}

我随意选择了这些大素数 - 我不知道它们是否真的具有加密安全性(例如p-1q-1是否具有必要的因子分解属性)。如果你确实需要安全性,你应该保密这些数字(例如自己生成)。

此外,我使用输入种子来生成s(和s_0) - 相反,我可以使用固定的s(具有已知的良好属性,像一个很大的时期),并使用种子作为消息摘要的输入(连同我在这里使用的输入)。

当然,也可以直接使用消息摘要的输出,而不是仅将其用作BBS的索引。