[英]How do I replicate PHP's PRNG algorithm implementation in C#?
我創建了一個程序圖像生成器,它使用 PHP5 中內置的默認偽隨機數生成器。
我可以用mt_srand($id);
設置種子mt_srand($id);
並始終獲得相同的數字序列(使用mt_rand(0,255);
)。
在 PHP 和 C# 中以完全相同的方式工作的 PRNG 實現
例子:
PHP:
mt_srand(123);
echo mt_rand(0,255); //returns 34
echo mt_rand(0,255); //returns 102
echo mt_rand(0,255); //returns 57
echo mt_rand(0,255); //returns 212
echo mt_rand(0,255); //returns 183
C#:
setSeed(123);
print getRand(0,255); //returns 34
print getRand(0,255); //returns 102
print getRand(0,255); //returns 57
print getRand(0,255); //returns 212
print getRand(0,255); //returns 183
( ^ 函數名不是指現有的,命名只是為了舉例)
感謝您的提示!
我解決了我自己在 C# 和 PHP 中實現自定義 PRNG 算法的問題。
由於我很快就需要它並且沒有時間去了解整個 Mersenne Twister 理論和兩種語言的不兼容性(例如類型和運算符的不同行為......),我決定編寫一個非常簡單的 PRNG 算法:
C#
代碼:
using System;
public class CiaccoRandom
{
private static int tree=0;
public void plantSeed(int seed)
{
tree = Math.Abs(seed) % 9999999+1;
getRand(0, 9999999);
}
public int getRand(int min, int max)
{
tree = (tree*125)%2796203;
return tree%(max-min+1)+min;
}
}
用法:
int seed = 123;
int min = 0;
int max = 255;
CiaccoRandom randomer = new CiaccoRandom();
randomer.plantSeed(seed);
randomer.getRand(min, max); // returns a pseudo-random int
PHP
代碼:
namespace ciacco_twister;
class CiaccoRandom {
private static $tree = 0;
public static function plantSeed($seed) {
self::$tree = abs(intval($seed)) % 9999999+1;
self::getRand();
}
public static function getRand($min = 0, $max = 9999999) {
self::$tree = (self::$tree * 125) % 2796203;
return self::$tree % ($max - $min + 1) + $min;
}
}
用法:
require_once "ciacco_twister.php";
use ciacco_twister\CiaccoRandom;
$seed = 123;
$min = 0;
$max = 255;
CiaccoRandom::plantSeed($seed);
CiaccoRandom::getRand($min,$max); // returns a pseudo-random int
筆記:
我需要一個 PRNG,在給定種子和 int 范圍的情況下,它始終會在 PHP 和 C# 中返回相同的 int 數字序列。
它非常有限,但它達到了它的目的!
也許它對其他人有用......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.