Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 34 additions & 3 deletions Semantics.Quantities/StorageMath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -812,20 +812,31 @@ private static T RootByDescent<T>(T value, int degree, T two)
T countLessOne = count - T.One;
T estimate = SeedForRoot(value, degree, two);

// The largest estimate known to be at or below the floor of the root. One is, since the value is
// greater than one.
T below = T.One;

// An estimate whose own power overflows is above the root, since the root's power divides a
// value the type holds, so the lift stops there as well as on a power that exceeds the value.
while (TryPower(estimate, degree, out T raised) && raised < value)
{
below = estimate;
estimate *= two;
}

for (int iteration = 0; iteration < MaximumIterations; iteration++)
{
if (!TryPower(estimate, degree - 1, out T power) || T.IsZero(power))
{
// The estimate is too large for its own power to be taken in the type. Halving reaches a
// range the type holds, and stays at or above the root.
estimate = (estimate + T.One) / two;
// The estimate is too large for its own power to be taken in the type, so it is above the
// root. Halving it could drop below the root, and a descent from there stops at once on a
// stale answer (#557), so bisect between it and the bound known to be at or below the floor.
if (estimate - below <= T.One)
{
return below;
}

(below, estimate) = Bisect(value, degree, two, below, estimate);
continue;
}

Expand All @@ -842,6 +853,26 @@ private static T RootByDescent<T>(T value, int degree, T two)
throw new ArithmeticException($"The root of degree {degree} did not reach its floor within {MaximumIterations} Newton steps.");
}

/// <summary>
/// Halves the range the floor of a root is known to lie in.
/// </summary>
/// <typeparam name="T">The numeric storage type, whose division floors.</typeparam>
/// <param name="value">The value to take the root of.</param>
/// <param name="degree">The degree of the root.</param>
/// <param name="two">Two, in <typeparamref name="T"/>.</param>
/// <param name="below">An estimate at or below the floor of the root.</param>
/// <param name="above">An estimate above the root, at least two more than <paramref name="below"/>.</param>
/// <returns>The narrower range: the midpoint replaces whichever bound it falls on the same side as.</returns>
private static (T Below, T Above) Bisect<T>(T value, int degree, T two, T below, T above)
where T : struct, INumber<T>
{
T middle = below + ((above - below) / two);

return TryPower(middle, degree, out T raised) && raised < value
? (middle, above)
: (below, middle);
}

/// <summary>
/// Takes the root in a type that keeps a fractional part, by settling on it.
/// </summary>
Expand Down
72 changes: 72 additions & 0 deletions Semantics.Test/Quantities/StorageMathTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,78 @@ public void ADegreeTooLargeForTheTypeToSquareStillAnswers()
Assert.AreEqual(1, StorageMath.RootN(int.MaxValue, 40));
}

/// <summary>
/// An exact power whose root the lift doubles past in a narrow type still roots to itself (#557):
/// the estimate's own power overflows there, and halving it used to drop below the root, so the
/// descent stopped at once one short of it.
/// </summary>
[TestMethod]
public void AnExactPowerInANarrowTypeRootsToItsRoot()
{
Assert.AreEqual((short)5, StorageMath.RootN((short)15625, 6));
Assert.AreEqual((short)4, StorageMath.RootN((short)16384, 7));
Assert.AreEqual(19, StorageMath.RootN(893871739, 7));
Assert.AreEqual(20, StorageMath.RootN(1280000000, 7));
Assert.AreEqual(21, StorageMath.RootN(1801088541, 7));
Assert.AreEqual((byte)3, StorageMath.RootN((byte)244, 5));
Assert.AreEqual(5, StorageMath.RootN(1220703126, 13));
}

/// <summary>
/// Every exact power the narrow integer types hold, and the values one either side of it, root to
/// the <see cref="BigInteger"/> floor of their root for degrees three to sixteen. One above an exact
/// power is where the bisection closes on the floor from an estimate whose power overflows, as
/// <c>RootN((byte)244, 5)</c> and <c>RootN(1220703126, 13)</c> do.
/// </summary>
[TestMethod]
public void TheNarrowIntegerTypesRootEveryExactPowerToItsFloor()
{
AssertFloorRootsAtExactPowers<sbyte>();
AssertFloorRootsAtExactPowers<byte>();
AssertFloorRootsAtExactPowers<short>();
AssertFloorRootsAtExactPowers<ushort>();
AssertFloorRootsAtExactPowers<int>();
AssertFloorRootsAtExactPowers<uint>();
}

private static void AssertFloorRootsAtExactPowers<T>()
where T : struct, IBinaryInteger<T>, IMinMaxValue<T>
{
BigInteger maximum = BigInteger.CreateChecked(T.MaxValue);

for (int degree = 3; degree <= 16; degree++)
{
for (BigInteger root = 2; BigInteger.Pow(root, degree) <= maximum; root++)
{
BigInteger power = BigInteger.Pow(root, degree);

foreach (BigInteger value in (BigInteger[])[power - 1, power, power + 1])
{
if (value > maximum)
{
continue;
}

BigInteger expected = FloorRoot(value, degree);
T actual = StorageMath.RootN(T.CreateChecked(value), degree);
Assert.AreEqual(expected, BigInteger.CreateChecked(actual), $"{typeof(T).Name}: RootN({value}, {degree})");
}
}
}
}

private static BigInteger FloorRoot(BigInteger value, int degree)
{
BigInteger root = 0;

while (BigInteger.Pow(root + 1, degree) <= value)
{
root++;
}

return root;
}

/// <summary>
/// An even root of a negative value has no real answer, and says so exactly as the square root does.
/// </summary>
Expand Down
Loading