2016-02-08 48 views
-2

我正在將一些Javascript代碼轉換爲C#,並且對Google數學多線程以及函數如何有點麻煩。這實際上是Delphi隨機函數的一個版本 - 根據我的合作開發者。使用Google.Math.Long將JS轉換爲C#

在JavaScript中,我有這個。

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; 
} 

在C#中我有這個 - 到目前爲止。

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 
} 

最大值總是254並在第一時間_nextRandom運行seedValue是1024每個其他時間之後它的0(在C#)或空值(在JS)

這裏的輸出從C#只爲正值是正確的,負面的是不正確的

卡斯蒂將值作爲字節使得值幾乎匹配但不完全相同。

有沒有人有任何想法,爲什麼發生這種情況?

回答

1

兩個問題:

  • 您已經聲明_seed是一個64位long。它應該是一個32位的int
  • 在執行64位乘法之前,您需要將_seedmaxValue改爲uint

下面的C#代碼複製德爾福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); 
} 

顯然這個代碼是不是線程安全的,但我相信你已經知道了。一個更清晰的實現是將其包裝在一個類中,以便可以用自己的種子創建PRNG的不同實例。