简体   繁体   中英

How to generate a set of random numbers in both Lua and C# that are the same?

我需要从Lua中的种子生成一组随机数,然后在同一种子的c#中生成相同的随机数集,最好的方法是什么?

You'll need the same code to generate the same random numbers. The Lua library is uncomplicated and passes the job to the C runtime library . That makes it somewhat likely that you'll get the same numbers if you use it as well. Easy to do with pinvoke:

using System.Runtime.InteropServices;
...
    public static double LuaRandom() {
        const int RAND_MAX = 0x7fff;
        return (double)(rand() % RAND_MAX) / RAND_MAX;
    }

    public static void LuaRandomSeed(int seed) {
        srand(seed);
    }

    [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern int rand();
    [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
    private static extern void srand(int seed);

Write a little test program in both Lua and C#, be sure to use LuaRandomSeed() and math.randomseed() so they start at the same sequence and compare the first ~25 numbers they spit out. If you don't get a match then your Lua implementation is using a different C runtime library and you'll have to write your own random number generator. The simple LCG that Microsoft uses:

private static uint seed;

public static int rand() {
    seed = seed * 214013 + 2531011;
    return (int)((seed >> 16) % RAND_MAX);
}

You need 2 random generators that use the same algorithm and parameters.

The .NET framework does not guarantee anything about the generator (ie it could change in a future version). I don't know much about Lua but it probably has a standard generator based on the implementing platform with similar vagaries.

So your most reliable course would be to pick an algorithm and implement it yourself on both platforms. And then all you need is a common seed to generate identical sequences.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM