Skip to content

Commit

Permalink
Fix values equiprobability for generating random BigInteger.
Browse files Browse the repository at this point in the history
  • Loading branch information
TheSquidCombatant committed Oct 16, 2023
1 parent 4fe9e78 commit 16d0ea4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class NextBigIntegerExtensionTests
[DataRow(10000, 100)]
[DataRow(100000, 10)]
[DataRow(1000000, 1)]
public void NextBigIntegerRandomTest(int iterationsCount, int borderValueLength)
public void NextBigIntegerRandomRangeTest(int iterationsCount, int borderValueLength)
{
var random = new Random(DateTime.Now.Millisecond);

Expand Down Expand Up @@ -50,5 +50,41 @@ public void NextBigIntegerRandomTest(int iterationsCount, int borderValueLength)
Assert.IsTrue(result <= max, message, min, max, result);
}
}

/// <summary>
/// Checks that any value within a given range can be generated.
/// </summary>
[TestMethod]
[DataRow(1000000, 10, 100)]
[DataRow(1000000, 100, 100)]
[DataRow(1000000, 1000, 100)]
public void NextBigIntegerRandomEquiprobabilityTest(int iterationsCount, int randomRangeSize, int maxDigitsCount)
{
var random = new Random(DateTime.Now.Millisecond);
var maxValueRaw = new StringBuilder(random.Next(1, 10).ToString(), maxDigitsCount);

for (int i = 1; i < maxDigitsCount; ++i)
{
maxValueRaw.Append(random.Next(0, 10));
}

var maxValue = BigInteger.Parse(maxValueRaw.ToString());
var minValue = maxValue - randomRangeSize + 1;
var resultCounter = new int[randomRangeSize];

for (int i = 0; i < iterationsCount; ++i)
{
var result = random.NextBigInteger(minValue, maxValue);
var index = (int)(result - minValue);
++resultCounter[index];
}

const string message = "value={0}, count={1}";

for (int i = 0; i < randomRangeSize; ++i)
{
Assert.IsTrue(resultCounter[i] > 0, message, i + minValue, resultCounter[i]);
}
}
}
}
7 changes: 4 additions & 3 deletions TheSquid.Numerics.Extensions/NextBigIntegerExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ public static BigInteger NextBigInteger(this Random random, BigInteger min, BigI
const string maxCannotBeLessMessage = "Max value can not be less then min value.";
if (max < min) throw new ArgumentOutOfRangeException(maxCannotBeLessMessage);
var residual = max - min;
if (residual == 0) return max;
var buffer = residual.ToByteArray();
random.NextBytes(buffer);
var multiplier = new BigInteger(buffer);
var addendum = residual & multiplier;
if (addendum < 0) addendum *= -1;
return min + addendum;
if (multiplier < 0) multiplier *= -1;
if (multiplier > residual) multiplier %= residual;
return min + multiplier;
}
}
}

0 comments on commit 16d0ea4

Please sign in to comment.