好了,我刚刚拿起了一个硬件RNG,它包含一些简单的函数,如下所示:
GetRandomBytes(UInt Length,out object Array)
GetRandomDoubles(UInt Length,out object Array)这些函数似乎很好地解释了自己,如何有效地使用这些函数来生成某个范围内的数字?
更多信息来自我们找到的一些文档,
GetRandomByte
Return a single byte containing 8 random bits.
GetRandomWord
Return an unsigned integer containing 32 random bits.
GetRandomDouble
Returns a double-precision floating point value uniformly
distributed between 0 (inclusive) and 1 (exclusive).
GetRandomBytes
GetRandomWords
GetRandomDoubles
Fill in an array with random values. These methods all take
two arguments, an integer specifying the number of values
to return (as an unsigned long integer), and the array to
return the values in (as a COM Variant).发布于 2010-07-26 00:21:46
要获得给定范围内的随机int,可以使用硬件提供的GetRandomDouble函数,并缩放该值以适合所需的范围。最大值是独占的,因为底层的双精度范围[0,1]是半开放的。
int GetRandomInt(int min, int max) {
double d = randHardware.GetRandomDouble();
return ((max-min)*d)+min;
}发布于 2010-07-21 00:19:09
如果我在没有任何其他帮助或指示的情况下拥有这些函数,我会做的第一个尝试是这样的(只需查看签名):
uint length = 20;
object array;
GetRandomBytes(length, out array);然后,我将尝试对其进行调试,并在调用该函数后查看array的实际类型。看一下函数的名称,我会假设为byte[],所以我会强制转换:
byte[] result = (byte[])array;就范围而言,这些函数签名远不是自解释的。也许是length参数?
还要注意的是,在C#中没有UInt这样的东西。有System.UInt32和uint,这是一条捷径。
发布于 2010-07-21 00:21:42
注意:这使用了包含范围。你可能想要独占的max,这是很典型的。显然,这应该根据您的需要进行修改。
假设你得到了一个随机的双倍
public int getIntInRangeFromDouble(int min, int max, double rand) {
int range = max-min+1;
int offset = (int)(range*rand);
return min + offset - 1;
}你可以通过使用你的随机替身来应用这个方法
int[] getIntsFromRandomDoubles(int min, int max, double[] rands) {
int[] result = new int[rands.length];
for(int i = 0; i < rands.length; i++) result[i] = getIntInRangeFromDouble(min,max,rands[i]);
return result;
}https://stackoverflow.com/questions/3292069
复制相似问题