Browse Source

Random: protected RandomSource.DoSampleBytes for clearer design around byte-based sampling

pull/428/head
Christoph Ruegg 10 years ago
parent
commit
ef808bbf30
  1. 8
      src/Numerics/Random/CryptoRandomSource.cs
  2. 25
      src/Numerics/Random/RandomSource.cs
  3. 5
      src/Numerics/Random/SystemRandomSource.cs

8
src/Numerics/Random/CryptoRandomSource.cs

@ -84,6 +84,14 @@ namespace MathNet.Numerics.Random
_crypto = rng;
}
/// <summary>
/// Fills the elements of a specified array of bytes with random numbers in full range, including zero and 255 (<see cref="F:System.Byte.MaxValue"/>).
/// </summary>
protected override void DoSampleBytes(byte[] buffer)
{
_crypto.GetBytes(buffer);
}
/// <summary>
/// Returns a random double-precision floating point number greater than or equal to 0.0, and less than 1.0.
/// </summary>

25
src/Numerics/Random/RandomSource.cs

@ -339,7 +339,7 @@ namespace MathNet.Numerics.Random
/// </summary>
/// <param name="buffer">An array of bytes to contain random numbers.</param>
/// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null. </exception>
public override void NextBytes(byte[] buffer)
public sealed override void NextBytes(byte[] buffer)
{
if (buffer == null)
{
@ -350,19 +350,13 @@ namespace MathNet.Numerics.Random
{
lock (_lock)
{
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)(DoSampleInteger()%256);
}
DoSampleBytes(buffer);
}
return;
}
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)(DoSampleInteger()%256);
}
DoSampleBytes(buffer);
}
/// <summary>
@ -388,7 +382,7 @@ namespace MathNet.Numerics.Random
protected abstract double DoSample();
/// <summary>
/// Returns a random 32-bit signed integer greater than or equal to zero and less than <see cref="F:System.Int32.MaxValue"/>.
/// Returns a random 32-bit signed integer greater than or equal to zero and less than 2147483647 (<see cref="F:System.Int32.MaxValue"/>).
/// </summary>
protected virtual int DoSampleInteger()
{
@ -404,5 +398,16 @@ namespace MathNet.Numerics.Random
{
return (int)(DoSample()*(maxExclusive - minInclusive)) + minInclusive;
}
/// <summary>
/// Fills the elements of a specified array of bytes with random numbers in full range, including zero and 255 (<see cref="F:System.Byte.MaxValue"/>).
/// </summary>
protected virtual void DoSampleBytes(byte[] buffer)
{
for (var i = 0; i < buffer.Length; i++)
{
buffer[i] = (byte)(DoSampleInteger() % 256);
}
}
}
}

5
src/Numerics/Random/SystemRandomSource.cs

@ -136,6 +136,11 @@ namespace MathNet.Numerics.Random
return _random.Next(minInclusive, maxExclusive);
}
protected override void DoSampleBytes(byte[] buffer)
{
_random.NextBytes(buffer);
}
/// <summary>
/// Fill an array with uniform random numbers greater than or equal to 0.0 and less than 1.0.
/// WARNING: potentially very short random sequence length, can generate repeated partial sequences.

Loading…
Cancel
Save