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
22 changes: 22 additions & 0 deletions PreciseNumber.Test/PreciseNumberExponentialTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,28 @@ public void TestLogRejectsValuesOutsideItsDomain()
Assert.ThrowsExactly<ArgumentOutOfRangeException>(() => PreciseNumber.Log(2.ToPreciseNumber(), 0));
}

[TestMethod]
public void TestLogInABaseNamesTheArgumentOutsideTheDomain()
{
// The base is passed on to the single-argument Log, whose guard names x, so each argument has
// to be checked under its own name first.
ArgumentOutOfRangeException negativeBase = Assert.ThrowsExactly<ArgumentOutOfRangeException>(
() => PreciseNumber.Log(5.ToPreciseNumber(), (-2).ToPreciseNumber()));
Assert.AreEqual("newBase", negativeBase.ParamName);
Assert.AreEqual((-2).ToPreciseNumber(), negativeBase.ActualValue);

ArgumentOutOfRangeException zeroBase = Assert.ThrowsExactly<ArgumentOutOfRangeException>(
() => PreciseNumber.Log(5.ToPreciseNumber(), PreciseNumber.Zero, 20));
Assert.AreEqual("newBase", zeroBase.ParamName);

ArgumentOutOfRangeException negativeValue = Assert.ThrowsExactly<ArgumentOutOfRangeException>(
() => PreciseNumber.Log((-5).ToPreciseNumber(), 2.ToPreciseNumber()));
Assert.AreEqual("x", negativeValue.ParamName);

// A base of one is still a division by its zero logarithm.
Assert.ThrowsExactly<DivideByZeroException>(() => PreciseNumber.Log(5.ToPreciseNumber(), PreciseNumber.One));
}

[TestMethod]
public void TestExpMatchesPublishedDigits()
{
Expand Down
13 changes: 13 additions & 0 deletions PreciseNumber/PreciseNumber.Exponentials.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,19 @@ public static PreciseNumber Log(PreciseNumber x, PreciseNumber newBase) =>
public static PreciseNumber Log(PreciseNumber x, PreciseNumber newBase, int significantDigits)
{
RequireSignificantDigits(significantDigits);

// Each argument is checked under its own name before either logarithm is worked out, so a bad
// base is not reported as a bad value by the single-argument Log it would otherwise reach.
if (x.Significand.Sign <= 0)
{
throw new ArgumentOutOfRangeException(nameof(x), x, NonPositiveLogarithmMessage);
}

if (newBase.Significand.Sign <= 0)
{
throw new ArgumentOutOfRangeException(nameof(newBase), newBase, NonPositiveLogarithmMessage);
}

int working = significantDigits + ExponentialGuardDigits;
return DivideApproximation(Log(x, working), Log(newBase, working), working, significantDigits);
}
Expand Down
Loading