views:

95

answers:

3

Ok, I've just picked up a hardware RNG and it contains some simple functions as below,

GetRandomBytes(UInt Length,out object Array)
GetRandomDoubles(UInt Length,out object Array)

The functions seem to explain themselves pretty well, how would one use these functions effectivly to generate a number between a certain range?

More info from some docs we have found,

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).
A: 

If I had those functions without absolutely any other help or indication the first try I would do is this (just looking at the signature):

uint length = 20;
object array;
GetRandomBytes(length, out array);

Then I will try to debug this and see what the actual type of array is after calling the function. Looking at the name of the function I would assume byte[], so I would cast:

byte[] result = (byte[])array;

As far as a range is concerned those function signatures are far from self-explaining. Maybe the length parameter?

Also note that in C# there's no such thing as UInt. There's System.UInt32 and uint which is a shortcut.

Darin Dimitrov
Updated main post with more info
Pino
A: 

NOTE: This uses inclusive ranges. You might want exclusive max, as is typical. Obviously this should be modified to your needs.

Let's say you get a double that's random

public int getIntInRangeFromDouble(int min, int max, double rand) {
    int range = max-min+1;
    int offset = (int)(range*rand);
    return min + offset - 1;
}

You can apply this by taking your random doubles and doing

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;
}
glowcoder
Btw, I'm a Java guy, not a C# guy. If I messed up some C# syntax, feel free to fix it or let me know! :)
glowcoder
Updated main post with more info
Pino
+2  A: 

To get a random int within a given range, you can use the GetRandomDouble function that is provided by the hardware, and scale that value to fit the desired range. The maximum value is exclusive, since the underlying double range [0,1) is half-open.

int GetRandomInt(int min, int max) {
   double d = randHardware.GetRandomDouble();
   return ((max-min)*d)+min;
}
mdma