add precomputed mathematical constants and specialize the second division residual
.NET Test / .NET tests (push) Successful in 2m23s

This commit is contained in:
2026-09-14 21:21:48 +04:00
parent 08036a31d5
commit 4efecbb1bc
11 changed files with 875 additions and 24 deletions
@@ -6,6 +6,303 @@ namespace Just.PreciseMath.Tests;
public class DoubleDoubleArithmeticTests
{
[Theory]
[InlineData(6.0, 2.0, 8.0, 4.0, 12.0, 3.0)]
[InlineData(-6.0, 2.0, -4.0, -8.0, -12.0, -3.0)]
[InlineData(6.0, -2.0, 4.0, 8.0, -12.0, -3.0)]
[InlineData(-6.0, -2.0, -8.0, -4.0, 12.0, 3.0)]
[InlineData(1.5, 0.5, 2.0, 1.0, 0.75, 3.0)]
[InlineData(-1.5, 0.5, -1.0, -2.0, -0.75, -3.0)]
[InlineData(0.75, 1.5, 2.25, -0.75, 1.125, 0.5)]
[InlineData(0.0, 2.0, 2.0, -2.0, 0.0, 0.0)]
[InlineData(2.0, 2.0, 4.0, 0.0, 4.0, 1.0)]
public void BasicArithmeticHasExactDyadicResults(double left, double right,
double sum, double difference, double product, double quotient)
{
// Small integers and binary fractions: each expected result is an exact
// rational representable in binary64, so no accuracy tolerance is needed.
DoubleDouble a = new(left);
DoubleDouble b = new(right);
CheckBoundary(a + b, sum, 0.0);
CheckBoundary(a + right, sum, 0.0);
CheckBoundary(left + b, sum, 0.0);
CheckBoundary(a - b, difference, 0.0);
CheckBoundary(a - right, difference, 0.0);
CheckBoundary(left - b, difference, 0.0);
CheckBoundary(a * b, product, 0.0);
CheckBoundary(a * right, product, 0.0);
CheckBoundary(left * b, product, 0.0);
CheckBoundary(a / b, quotient, 0.0);
CheckBoundary(a / right, quotient, 0.0);
CheckBoundary(left / b, quotient, 0.0);
}
[Theory]
[InlineData(30.0, 0.5235987755982989, -5.360408832255455e-17)]
[InlineData(45.0, 0.7853981633974483, 3.061616997868383e-17)]
[InlineData(60.0, 1.0471975511965979, -1.072081766451091e-16)]
[InlineData(90.0, 1.5707963267948966, 6.123233995736766e-17)]
[InlineData(180.0, 3.141592653589793, 1.2246467991473532e-16)]
[InlineData(360.0, 6.283185307179586, 2.4492935982947064e-16)]
public void AngleConversionConstantsRetainExtendedPrecision(double degrees, double radiansHigh, double radiansLow)
{
// Independent precomputed pi fractions from ReferenceData/generate_constants.py.
// Check each direction against its own reference, not a computed round trip.
foreach (double sign in new[] { -1.0, 1.0 })
{
double signedDegrees = sign * degrees;
BigInteger radiansUnits = Units(sign * radiansHigh) + Units(sign * radiansLow);
AssertRelative(signedDegrees * DoubleDouble.DegToRad, radiansUnits, BigInteger.One);
AssertRelative(DoubleDouble.DegToRad * signedDegrees, radiansUnits, BigInteger.One);
AssertRelative(new DoubleDouble(signedDegrees) * DoubleDouble.DegToRad, radiansUnits, BigInteger.One);
DoubleDouble radians = DoubleDouble.FromComponents(sign * radiansHigh, sign * radiansLow);
AssertRelative(radians * DoubleDouble.RadToDeg, Units(signedDegrees), BigInteger.One);
AssertRelative(DoubleDouble.RadToDeg * radians, Units(signedDegrees), BigInteger.One);
}
}
// Generated by: python3 1-tests/Just.PreciseMath.Tests/ReferenceData/generate_irrational_arithmetic.py
// Constants: Python Decimal at 160 digits, checked again at 240 digits;
// pi uses Machin's formula, e/roots/ln use Decimal's exp/sqrt/ln, phi=(1+sqrt(5))/2.
// Expected operations use exact Fraction sums of the stored input components,
// then round high and residual separately to binary64. A scalar input has no low.
// Column pairs: left, right, sum, difference, product, quotient.
[Theory]
// pi, e: DD/DD
[InlineData("DD/DD",
3.141592653589793, 1.2246467991473532e-16,
2.718281828459045, 1.4456468917292502e-16,
5.859874482048839, -1.7705984076240228e-16,
0.423310825130748, -2.2100009258189695e-17,
8.539734222673568, -6.773815290502424e-16,
1.1557273497909217, -1.3998972600526045e-17)]
// pi, e: DD/double
[InlineData("DD/double",
3.141592653589793, 1.2246467991473532e-16,
2.718281828459045, 0.0,
5.859874482048839, -3.2162452993532727e-16,
0.42331082513074814, 1.1442377452219667e-17,
8.539734222673566, 6.44811944875855e-16,
1.1557273497909217, 4.746535510161172e-17)]
// pi, e: double/DD
[InlineData("double/DD",
3.141592653589793, 0.0,
2.718281828459045, 1.4456468917292502e-16,
5.859874482048839, -2.995245206771376e-16,
0.42331082513074786, 2.1968764520848465e-17,
8.539734222673566, 7.660817963097297e-16,
1.1557273497909217, -5.905121061079843e-17)]
// sqrt2, sqrt3: DD/DD
[InlineData("DD/DD",
1.4142135623730951, -9.667293313452913e-17,
1.7320508075688772, 1.0035084221806903e-16,
3.1462643699419726, -2.1836669584149143e-16,
-0.31783724519578227, 2.5020829572433146e-17,
2.449489742783178, 2.168616518103246e-16,
0.816496580927726, -1.7276510382355668e-18)]
// sqrt2, sqrt3: DD/double
[InlineData("DD/double",
1.4142135623730951, -9.667293313452913e-17,
1.7320508075688772, 0.0,
3.146264369941972, 1.2537167179050217e-16,
-0.31783724519578216, 1.434936932798652e-17,
2.449489742783178, 7.494412974996883e-17,
0.816496580927726, 4.5578189648549696e-17)]
// sqrt2, sqrt3: double/DD
[InlineData("double/DD",
1.4142135623730951, 0.0,
1.7320508075688772, 1.0035084221806903e-16,
3.1462643699419726, -1.2169376270696227e-16,
-0.31783724519578216, 1.0671460244446626e-17,
2.4494897427831783, -5.978512613402474e-17,
0.816496580927726, 5.408649293033552e-17)]
// ln2, phi: DD/DD
[InlineData("DD/DD",
0.6931471805599453, 2.3190468138462996e-17,
1.618033988749895, -5.432115203682506e-17,
2.3111811693098403, -1.421529863608777e-16,
-0.9248868081899495, -3.35106822872276e-17,
1.121535697352152, -9.053143373999594e-17,
0.4283885167922066, -2.699599415943276e-18)]
// ln2, phi: DD/double
[InlineData("DD/double",
0.6931471805599453, 2.3190468138462996e-17,
1.618033988749895, 0.0,
2.3111811693098403, -8.783183432405266e-17,
-0.9248868081899496, 2.3190468138462996e-17,
1.121535697352152, -5.2878880360902515e-17,
0.4283885167922066, -1.708159504353726e-17)]
// ln2, phi: double/DD
[InlineData("double/DD",
0.6931471805599453, 0.0,
1.618033988749895, -5.432115203682506e-17,
2.3111811693098403, -1.653434544993407e-16,
-0.9248868081899496, 5.432115203682506e-17,
1.1215356973521518, 9.399020552198074e-17,
0.4283885167922066, -1.703209694053491e-17)]
public void BasicArithmeticMatchesPrecomputedIrrationalResults(string overload,
double leftHigh, double leftLow, double rightHigh, double rightLow,
double sumHigh, double sumLow, double differenceHigh, double differenceLow,
double productHigh, double productLow, double quotientHigh, double quotientLow)
{
foreach (double sign in new[] { -1.0, 1.0 })
{
DoubleDouble left = DoubleDouble.FromComponents(sign * leftHigh, sign * leftLow);
DoubleDouble right = DoubleDouble.FromComponents(sign * rightHigh, sign * rightLow);
(DoubleDouble sum, DoubleDouble difference, DoubleDouble product, DoubleDouble quotient) = overload switch
{
"DD/DD" => (left + right, left - right, left * right, left / right),
"DD/double" => (left + right.High, left - right.High, left * right.High, left / right.High),
"double/DD" => (left.High + right, left.High - right, left.High * right, left.High / right),
_ => throw new ArgumentOutOfRangeException(nameof(overload))
};
// Negating both inputs negates sum/difference but not product/quotient.
// Compare complete expansions at the established 2^-100 relative + epsilon bound,
// not individual component equality: correct rounding is not guaranteed.
// The generator checks reference-rounding error is below 2^-105 relative.
AssertRelative(sum, Units(sign * sumHigh) + Units(sign * sumLow), BigInteger.One);
AssertRelative(difference, Units(sign * differenceHigh) + Units(sign * differenceLow), BigInteger.One);
AssertRelative(product, Units(productHigh) + Units(productLow), BigInteger.One);
AssertRelative(quotient, Units(quotientHigh) + Units(quotientLow), BigInteger.One);
}
}
[Theory]
[InlineData("+", "DD/DD")]
[InlineData("-", "DD/DD")]
[InlineData("*", "DD/DD")]
[InlineData("/", "DD/DD")]
[InlineData("+", "DD/double")]
[InlineData("-", "DD/double")]
[InlineData("*", "DD/double")]
[InlineData("/", "DD/double")]
[InlineData("+", "double/DD")]
[InlineData("-", "double/DD")]
[InlineData("*", "double/DD")]
[InlineData("/", "double/DD")]
public void GeneralArithmeticMeetsExactRationalBound(string operation, string overload)
{
// Fixed seed, with dense, sparse and zero residuals independent of the
// high sign. Include ordinary exponents as well as dispatch/range edges.
// Every pair is checked in both orders; overflow cases are asserted, not skipped.
Random random = new(65537);
int[] exponents = [-1074, -1022, -969, -451, -450, -1, 0, 1, 450, 451, 900, 1020, 1021, 1023];
foreach (int leftExponent in exponents)
{
foreach (int rightExponent in exponents)
{
for (int sample = 0; sample < 4; ++sample)
{
DoubleDouble left = GeneralArithmeticSample(random, leftExponent, sample);
DoubleDouble right = GeneralArithmeticSample(random, rightExponent, (sample + 1) % 4);
AssertGeneralArithmetic(left, right, operation, overload);
AssertGeneralArithmetic(right, left, operation, overload);
}
}
}
for (int sample = 0; sample < 512; ++sample)
{
int exponent = random.Next(-450, 451);
DoubleDouble left = GeneralArithmeticSample(random, exponent, sample % 4);
DoubleDouble right = GeneralArithmeticSample(random, random.Next(-450, 451), (sample + 1) % 4);
AssertGeneralArithmetic(left, right, operation, overload);
AssertGeneralArithmetic(right, left, operation, overload);
// Correlate highs to force cancellation rather than hoping random
// independent values happen to exercise it. Keep different low terms.
DoubleDouble neighbor = DoubleDouble.FromComponents(left.High, -left.Low);
AssertGeneralArithmetic(left, neighbor, operation, overload);
AssertGeneralArithmetic(left, -neighbor, operation, overload);
}
}
private static DoubleDouble GeneralArithmeticSample(Random random, int exponent, int residualKind)
{
double sign = random.Next(2) == 0 ? -1.0 : 1.0;
double high = Math.ScaleB(sign * (1.0 + (0.75 * random.NextDouble())), exponent);
double low = residualKind switch
{
0 => 0.0,
1 => Math.ScaleB(random.NextDouble() - 0.5, exponent - 53),
2 => Math.ScaleB(random.NextDouble() - 0.5, exponent - 106),
3 => random.Next(2) == 0 ? -double.Epsilon : double.Epsilon,
_ => throw new ArgumentOutOfRangeException(nameof(residualKind))
};
// At the subnormal floor a residual can cancel the high completely.
// Use a scalar there so this finite-input matrix never divides by zero;
// the separate special-value matrix covers zero denominators and NaNs.
if (exponent < -1022)
{
low = 0.0;
}
DoubleDouble result = DoubleDouble.FromComponents(high, low);
double.IsFinite(result.High).ShouldBeTrue();
result.High.ShouldNotBe(0.0);
return result;
}
private static void AssertGeneralArithmetic(DoubleDouble left, DoubleDouble right, string operation, string overload)
{
DoubleDouble actual = (operation, overload) switch
{
("+", "DD/DD") => left + right,
("-", "DD/DD") => left - right,
("*", "DD/DD") => left * right,
("/", "DD/DD") => left / right,
("+", "DD/double") => left + right.High,
("-", "DD/double") => left - right.High,
("*", "DD/double") => left * right.High,
("/", "DD/double") => left / right.High,
("+", "double/DD") => left.High + right,
("-", "double/DD") => left.High - right,
("*", "double/DD") => left.High * right,
("/", "double/DD") => left.High / right,
_ => throw new ArgumentOutOfRangeException(nameof(operation))
};
// Units decodes both IEEE-754 components independently of library arithmetic.
// Expected numerator/denominator is measured in units of epsilon, not doubles.
BigInteger x = overload == "double/DD" ? Units(left.High) : Units(left);
BigInteger y = overload == "DD/double" ? Units(right.High) : Units(right);
(BigInteger numerator, BigInteger denominator) = operation switch
{
"+" => (x + y, BigInteger.One),
"-" => (x - y, BigInteger.One),
"*" => (x * y, BigInteger.One << 1074),
"/" => (x << 1074, y),
_ => throw new ArgumentOutOfRangeException(nameof(operation))
};
if (denominator.Sign < 0)
{
numerator = -numerator;
denominator = -denominator;
}
string context = $"{overload}: ({left.High:R}, {left.Low:R}) {operation} ({right.High:R}, {right.Low:R}); "
+ $"actual ({actual.High:R}, {actual.Low:R})";
// Nearest-even binary64 overflow begins at 2^1024 - 2^970.
BigInteger overflowUnits = Units(double.MaxValue) + Units(Math.ScaleB(1.0, 970));
if (BigInteger.Abs(numerator) >= overflowUnits * denominator)
{
actual.High.ShouldBe(numerator.Sign < 0 ? double.NegativeInfinity : double.PositiveInfinity, context);
BitConverter.DoubleToInt64Bits(actual.Low).ShouldBe(0L, context);
return;
}
double.IsFinite(actual.High).ShouldBeTrue(context);
double.IsFinite(actual.Low).ShouldBeTrue(context);
BigInteger error = BigInteger.Abs((Units(actual) * denominator) - numerator);
// Same conservative 2^-100 relative + epsilon contract as the existing
// suite, cross-multiplied exactly to retain all low-component information.
(error <= (BigInteger.Abs(numerator) >> 100) + denominator).ShouldBeTrue(context);
(actual.High + actual.Low).ShouldBe(actual.High, context);
if (actual.Low == 0.0)
{
BitConverter.DoubleToInt64Bits(actual.Low).ShouldBe(0L, context);
}
if (actual.High == 0.0)
{
// Exact cancellation is +0; a nonzero underflow keeps its sign.
BitConverter.DoubleToInt64Bits(actual.High).ShouldBe(numerator.Sign < 0 ? long.MinValue : 0L, context);
}
}
[Fact]
public void CancellationRetainsBothLowSumTerms()
{
@@ -232,6 +529,56 @@ public class DoubleDoubleArithmeticTests
AssertRelative(-1.0 / value, -numerator, Units(value));
}
[Fact]
public void DivisionNormalizesTheFirstCorrectionBeforeAddingTheLast()
{
// Exact rational: (1 + 2^-54) / (17/16 - 2^-54).
// Independently round that rational to binary64, then round its exact
// residual: high bits 3FEE1E1E1E1E1E1F, low bits 3C4FE3A76B2EF2C4.
// Adding the last correction to the unnormalized pair instead loses
// four low-component ULPs. Common power-of-two scaling preserves the ratio.
double expectedHigh = BitConverter.UInt64BitsToDouble(0x3fee_1e1e_1e1e_1e1f);
double expectedLow = BitConverter.UInt64BitsToDouble(0x3c4f_e3a7_6b2e_f2c4);
foreach (int exponent in new[] { -450, 0, 450 })
{
foreach (double leftSign in new[] { -1.0, 1.0 })
{
foreach (double rightSign in new[] { -1.0, 1.0 })
{
DoubleDouble left = DoubleDouble.FromComponents(leftSign * Math.ScaleB(1.0, exponent),
leftSign * Math.ScaleB(1.0, exponent - 54));
DoubleDouble right = DoubleDouble.FromComponents(rightSign * Math.ScaleB(1.0625, exponent),
-rightSign * Math.ScaleB(1.0, exponent - 54));
double sign = leftSign * rightSign;
DoubleDouble actual = left / right;
CheckBoundary(actual, sign * expectedHigh, sign * expectedLow);
AssertRelative(actual, Units(left) << 1074, Units(right));
}
}
}
}
[Fact]
public void DivisionSecondResidualPreservesBitsAndRationalAccuracy()
{
Random random = new(104729);
for (int i = 0; i < 4096; ++i)
{
int leftExponent = random.Next(-450, 451);
int rightExponent = random.Next(-450, 451);
double leftHigh = Math.ScaleB(1.0 + (0.75 * random.NextDouble()), leftExponent);
double rightHigh = Math.ScaleB(1.0 + (0.75 * random.NextDouble()), rightExponent);
double leftLow = i % 3 == 0 ? 0.0 : i % 3 == 1 ? double.Epsilon
: Math.ScaleB(random.NextDouble() - 0.5, leftExponent - 53);
double rightLow = i % 3 == 1 ? 0.0 : i % 3 == 2 ? -double.Epsilon
: Math.ScaleB(random.NextDouble() - 0.5, rightExponent - 53);
DoubleDouble left = DoubleDouble.FromComponents(i % 2 == 0 ? leftHigh : -leftHigh, leftLow);
DoubleDouble right = DoubleDouble.FromComponents(i % 4 < 2 ? rightHigh : -rightHigh, rightLow);
AssertDivisionMatchesPrevious(left, right);
AssertDivisionMatchesPrevious(right, left);
}
}
[Fact]
public void DivisionRetainsSubnormalCorrectionsWithOrdinaryHighComponents()
{
@@ -537,6 +884,21 @@ public class DoubleDoubleArithmeticTests
}
}
private static void AssertDivisionMatchesPrevious(DoubleDouble left, DoubleDouble right)
{
// Freeze the pre-specialization expression. The unchanged public operators
// form the bitwise reference; Units supplies the independent rational oracle.
double quotient = left.High / right.High;
DoubleDouble remainder = left - (right * quotient);
double correction = remainder.High / right.High;
remainder -= right * correction;
double finalCorrection = remainder.High / right.High;
DoubleDouble expected = DoubleDouble.FromComponents(quotient, correction) + finalCorrection;
DoubleDouble actual = left / right;
CheckBoundary(actual, expected.High, expected.Low);
AssertRelative(actual, Units(left) << 1074, Units(right));
}
private static void Check(DoubleDouble value, double high, double low)
{
value.High.ShouldBe(high);