Browse Source

Fix Issue #427

Use Fastpath without random-call when only a single value is allowed to be returned.
Added test that result of Next() is within boundaries.
netstandard
Juri 10 years ago
parent
commit
041ee94908
  1. 13
      src/Numerics/Random/RandomSource.cs
  2. 23
      src/UnitTests/Random/RandomTests.cs

13
src/Numerics/Random/RandomSource.cs

@ -472,6 +472,12 @@ namespace MathNet.Numerics.Random
/// </summary>
protected virtual long DoSampleInt64WithNBits(int bitCount)
{
// Fast case: Only 0 is allowed to be returned
// No random call is needed
if (bitCount == 0)
{
return 0;
}
var bytes = new byte[8];
DoSampleBytes(bytes);
@ -489,6 +495,13 @@ namespace MathNet.Numerics.Random
/// <param name="maxExclusive">The exclusive upper bound of the random number returned.</param>
protected virtual int DoSampleInteger(int maxExclusive)
{
// Fast case: Only a single number is allowed to be returned
// No random call is needed
if (maxExclusive == 1)
{
return 0;
}
// non-biased implementation
// (biased: return (int)(DoSample() * maxExclusive);)

23
src/UnitTests/Random/RandomTests.cs

@ -78,6 +78,29 @@ namespace MathNet.Numerics.UnitTests.Random
Assert.IsTrue(sum >= (N/2.0) - (.05*N));
Assert.IsTrue(sum <= (N/2.0) + (.05*N));
var disposable = random as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
/// <summary>
/// Next() result is in boundaries.
/// </summary>
[Test]
public void Boundaries()
{
var random = (System.Random)Activator.CreateInstance(_randomType, new object[] { false });
for (var i = 1; i < N; i++)
{
var j = N;
var next = random.Next(i, j);
Assert.IsTrue(next >= i, string.Format("Value {0} is smaller than lower bound {1}", next, i));
Assert.IsTrue(next < j, string.Format("Value {0} is larger or equal to upper bound {1}", next, j));
}
var disposable = random as IDisposable;
if (disposable != null)
{

Loading…
Cancel
Save