Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the Random Generator from Delphi the same calculation as C# if fed the same seed?

Tags:

c#

random

delphi

I'm translating some Delphi code into c# code when I ran into this. I don't have an environment setup for Delphi so I can't test it myself.

Delphi:

RandSeed := var1;
Result := Random($FF);

c#:

Random RandSeed = new Random(var1);
Result = RandSeed.Next(255);

Would these put the same value in Result? If not, any ideas on a way to do so?

like image 729
GluedHands Avatar asked Feb 11 '09 16:02

GluedHands


2 Answers

The Delphi PRNG is a deterministic linear congruential generator with 134775813 as a and 1 as c, and returning the high 32 bits for range-limited numbers. Here's an implementation in C# that returns the same values as Delphi:

using System;

class DelphiRandom
{
    int _seed;

    public DelphiRandom(int seed)
    {
        _seed = seed;
    }

    int GetNext() // note: returns negative numbers too
    {
        _seed = _seed * 0x08088405 + 1;
        return _seed;
    }

    public int Next(int maxValue)
    {
        ulong result = (ulong) (uint) GetNext() * (ulong) (uint) maxValue;
        return (int) (result >> 32);
    }
}

class App
{
    static void Main()
    {
        DelphiRandom r = new DelphiRandom(42);
        for (int i = 0; i < 10; ++i)
            Console.WriteLine(r.Next(100));
    }
}
like image 184
Barry Kelly Avatar answered Oct 13 '22 02:10

Barry Kelly


Certainly not, because they use different RNGs. You could perhaps use a RNG from the Windows API, create your own RNG or use some RNG library to achieve this.

Another way to make sure your RNG creates the same numbers for a given seed would be to write a DLL and use it for both Delphi and C#.

By the way, if you want to code a RNG yourself, Wikipedia is a good starting point to get the names of some usual generators. After you're done, you should run it through some statistical test to make sure it's "random" enough for you.

like image 45
schnaader Avatar answered Oct 13 '22 02:10

schnaader