Entries

笔记:.Net框架中的Random类的实现 / Note: The Random class in .Net FX

注意:这是SSCLI中Random.cs关键的一部分,并非完整的实现。代码版权归属于Microsoft,保留所有权力。
Notice: This is only the key part of Random.cs in SSCLI, not the whole.


// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: Random
**
**
** Purpose: A random number generator.
**
**
===========================================================*/

public class Random {
//
// Private Constants
//
private const int MBIG = Int32.MaxValue;
private const int MSEED = 161803398;
private const int MZ = 0;


//
// Member Variables
//
private int inext, inextp;
private int[] SeedArray = new int[56];

public Random()
: this(Environment.TickCount) {
}

public Random(int Seed) {
int ii;
int mj, mk;

//Initialize our Seed array.
//This algorithm comes from Numerical Recipes in C (2nd Ed.)
mj = MSEED - Math.Abs(Seed);
SeedArray[55] = mj;
mk = 1;
for (int i = 1; i < 55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
ii = (21 * i) % 55;
SeedArray[ii] = mk;
mk = mj - mk;
if (mk < 0) mk += MBIG;
mj = SeedArray[ii];
}
for (int k = 1; k < 5; k++) {
for (int i = 1; i < 56; i++) {
SeedArray[i] -= SeedArray[1 + (i + 30) % 55];
if (SeedArray[i] < 0) SeedArray[i] += MBIG;
}
}
inext = 0;
inextp = 21;
Seed = 1;
}



private int InternalSample() {
int retVal;
int locINext = inext;
int locINextp = inextp;

if (++locINext >= 56) locINext = 1;
if (++locINextp >= 56) locINextp = 1;

retVal = SeedArray[locINext] - SeedArray[locINextp];

if (retVal < 0) retVal += MBIG;

SeedArray[locINext] = retVal;

inext = locINext;
inextp = locINextp;

return retVal;
}
}
引用此文章(FC2博客用户)
http://shinron4.blog126.fc2blog.us/tb.php/24-4cf9913d

引用

留言

发表留言

发表留言
只对管理员显示

Appendix

自我介绍

优雅的神棍 / Elegant Tales

Author:优雅的神棍 / Elegant Tales
神棍你好,神棍再见。

最新引用

QR

QR

羔羊们啊

加为好友

和此人成爲好友

搜寻栏