Jjj February 2016

Converting JS Using Google.Math.Long to C#

I am converting some Javascript code into C# and having a bit of trouble with the Google math longs and how the function. This is actually a version of the Delphi random function - according to my co dev.

In javascript I have this.

function _nextRandom(maxValue, seedValue) {
    if (seedValue !== null) 
        _seed = new goog.math.Long(seedValue);

    _seed = _seed.multiply(134775813).add(_one);
    _seed = new goog.math.Long(_seed.getLowBitsUnsigned());
    return _seed.multiply(new goog.math.Long(maxValue)).getHighBits() >>> 0;
}

In C# I have this - so far.

private int _nextRandom(int maxValue, int seedValue)
{
    if (seedValue != 0)
        _seed = seedValue;

    _seed = _seed * 134775813 + 1;
    _seed = (long)((int)_seed); // get lower 32 bits
    return (int)(((ulong)_seed * (ulong)maxValue) >> 32); // get upper 32 bits
}

Max value is always 254 and the first time _nextRandom is run seedValue is 1024 every other time afterwards its 0 (in C#) or null (in JS)

Here the output from the C# is correct only for positive values, negative ones are incorrect

Casting the values as byte makes the values nearly match but not exactly.

Does anyone have any ideas why this is happening?

Answers


David Heffernan February 2016

A couple of problems:

  • You have declared _seed to be a 64 bit long. It should be a 32 bit int.
  • You need to cast _seed and maxValue to uint before performing the 64 bit multiplication.

The following C# code replicates the Delphi PRNG:

private static int _seed = 0;

private static int _nextRandom(int maxValue, int seedValue)
{
    if (seedValue != 0)
        _seed = seedValue;
    _seed = _seed * 0x08088405 + 1;
    return (int)(((ulong)(uint)_seed * (uint)maxValue) >> 32);
}

Obviously this code is not threadsafe but I am sure you already know that. A cleaner implementation would be to wrap this in a class so that you could create distinct instances of the PRNG with their own seed.

Post Status

Asked in February 2016
Viewed 3,754 times
Voted 12
Answered 1 times

Search




Leave an answer