Skip to content

Commit d41933e

Browse files
Take a compiled binomial of a large whole order through a ratio of gammas (#2340)
A compiled binomial(n, k) with a whole k is a product of k factors while k fits a long, and past that it went through the gamma function. Past the longs the logarithms of Γ(k + 1) and Γ(n - k + 1), both near k ln k, cancelled to their rounding error, and all three compilers answered 1: binomial(-5/2, 10^20) is 7.52e29, and binomial(277.7, 36!) is 2e-11027, which is 0 in a double. Within the longs, an n whose factors never take the product to 0 ran k steps: binomial(-1/2, 10^12) did not return. From an order of a million, with |n| at most half of it and n not a whole number at least 0, the binomial is now (-1)^k Γ(k - n)/(Γ(k + 1) Γ(-n)), with ln Γ(k - n) - ln Γ(k + 1) from Stirling's series written as differences, so that nothing near k ln k is subtracted, and ln(1 + z) by its series where z is small. Every double past 2^53 is even. A whole n at least 0 below such a k, and a negative k, are 0, as they are within the longs. 2.6.0 did not compile the binomial. The values in the test are mpmath's. Found by compilesweep at seed 13; no issue was filed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d5a279c commit d41933e

2 files changed

Lines changed: 119 additions & 1 deletion

File tree

‎Sources/AngouriMath/Numerics/CombinatorialFunctions.cs‎

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ private static bool IsWhole(NumericsComplex z, out long whole)
3434
{
3535
whole = 0;
3636
if (z.Imaginary != 0 || double.IsNaN(z.Real) || double.IsInfinity(z.Real)
37-
|| Math.Floor(z.Real) != z.Real || Math.Abs(z.Real) > 9e15)
37+
|| Math.Floor(z.Real) != z.Real || Math.Abs(z.Real) > LongestWhole)
3838
return false;
3939
whole = (long)z.Real;
4040
return true;
@@ -54,11 +54,21 @@ public static NumericsComplex Binomial(NumericsComplex n, NumericsComplex k)
5454
return 0;
5555
if (IsWhole(n, out var whole))
5656
return WholeBinomial(whole, lower);
57+
if (OfALargeWholeOrder(n, k.Real) is { } large)
58+
return large;
5759
NumericsComplex product = 1;
5860
for (long i = 0; i < lower && product != 0 && !IsInfinite(product); i++)
5961
product *= (n - i) / (i + 1);
6062
return product;
6163
}
64+
// Every double past the longs is whole: the cases above, for an order there.
65+
if (k.Imaginary == 0 && Math.Abs(k.Real) > LongestWhole && !double.IsInfinity(k.Real))
66+
{
67+
if (k.Real < 0 || n.Imaginary == 0 && Math.Floor(n.Real) == n.Real && n.Real >= 0 && k.Real > n.Real)
68+
return 0;
69+
if (OfALargeWholeOrder(n, k.Real) is { } large)
70+
return large;
71+
}
6272
if (IsWhole(n, out var negative) && negative < 0)
6373
return NaN;
6474
if (IsWhole(n - k, out var difference) && difference < 0)
@@ -270,6 +280,53 @@ private static double ProductOfWholeFactors(long first, long step, long count, b
270280
/// and <c>216!</c> about <c>1e408</c>, so the ratio was <c>∞/∞</c>, <c>NaN</c>. None of the ratios is 0 away from a
271281
/// pole, so a 0 is one whose terms were under the doubles. https://github.com/asc-community/AngouriMath/issues/2248
272282
/// </summary>
283+
// The largest whole number IsWhole takes.
284+
private const double LongestWhole = 9e15;
285+
286+
// From this order on, a binomial whose n is far below it is taken through the logarithm of a ratio of gammas.
287+
private const double LargeOrder = 1e6;
288+
289+
/// <summary>
290+
/// <c>binomial(n, k)</c> for a whole <paramref name="k"/> of at least a million and an <paramref name="n"/>
291+
/// at most half of it that is not a whole number at least 0: <c>(-1)^k Γ(k - n)/(Γ(k + 1) Γ(-n))</c>, with
292+
/// the logarithm of <c>Γ(k - n)/Γ(k + 1)</c> by <see cref="LogGammaRatio"/>; null for any other. As a product
293+
/// it took k steps, which for <c>binomial(-1/2, 10^12)</c>, whose factors never take it to 0, is 10^12; and past
294+
/// the longs it went through the gamma function, whose two logarithms near <c>k ln k</c> cancelled to their
295+
/// rounding error: <c>binomial(-5/2, 10^20)</c> was 1, where it is <c>7.52e29</c>.
296+
/// </summary>
297+
private static NumericsComplex? OfALargeWholeOrder(NumericsComplex n, double k)
298+
{
299+
if (k < LargeOrder || n.Magnitude > k / 2 || n.Imaginary == 0 && Math.Floor(n.Real) == n.Real && n.Real >= 0)
300+
return null;
301+
var value = FromLogarithm(LogGammaRatio(-n, 1, k) - SpecialFunctions.LogFactorial(-n - 1), n.Imaginary == 0);
302+
// Past 2^53 every double is even.
303+
return k < ExactBelow && ((long)k & 1) == 1 ? -value : value;
304+
}
305+
306+
/// <summary>
307+
/// <c>ln Γ(k + a) - ln Γ(k + b)</c> for a <paramref name="k"/> of at least a million and an <paramref name="a"/>
308+
/// and <paramref name="b"/> at most half of it, by Stirling's series written as differences, so that nothing
309+
/// near <c>k ln k</c> is subtracted: <c>(a - b) ln k + (k + a - 1/2) ln(1 + a/k) - (k + b - 1/2) ln(1 + b/k)
310+
/// - (a - b)</c> and the series' next two terms, whose remainder at <c>k/2</c> is below <c>10^-30</c>.
311+
/// </summary>
312+
private static NumericsComplex LogGammaRatio(NumericsComplex a, NumericsComplex b, double k)
313+
{
314+
NumericsComplex za = k + a, zb = k + b;
315+
return (a - b) * Math.Log(k) + (za - 0.5) * LogOnePlus(a / k) - (zb - 0.5) * LogOnePlus(b / k) - (a - b)
316+
+ (1 / za - 1 / zb) / 12 - (1 / (za * za * za) - 1 / (zb * zb * zb)) / 360;
317+
}
318+
319+
/// <summary><c>ln(1 + z)</c>, by its series where <c>z</c> is small, which <c>ln</c> of <c>1 + z</c> would round away.</summary>
320+
private static NumericsComplex LogOnePlus(NumericsComplex z)
321+
{
322+
if (z.Magnitude > 1e-3)
323+
return NumericsComplex.Log(1 + z);
324+
NumericsComplex sum = 0, power = z;
325+
for (var i = 1; i <= 7; i++, power *= -z)
326+
sum += power / i;
327+
return sum;
328+
}
329+
273330
private static bool InTheDoubles(NumericsComplex ratio)
274331
=> ratio != 0 && !IsInfinite(ratio) && !double.IsNaN(ratio.Real) && !double.IsNaN(ratio.Imaginary);
275332

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
//
2+
// Copyright (c) 2019-2026 Angouri.
3+
// AngouriMath is licensed under MIT.
4+
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
5+
// Website: https://am.angouri.org.
6+
//
7+
8+
using System;
9+
using System.Threading.Tasks;
10+
using AngouriMath.Extensions;
11+
using Xunit;
12+
using Complex = System.Numerics.Complex;
13+
14+
namespace AngouriMath.Tests.Common
15+
{
16+
/// <summary>
17+
/// A compiled <c>binomial(n, k)</c> for a whole <c>k</c> far past <c>n</c>. Past the longs it went through
18+
/// the gamma function, whose two logarithms near <c>k ln k</c> cancelled to their rounding error, and was 1:
19+
/// <c>binomial(-5/2, 10^20)</c> is <c>7.52e29</c> and <c>binomial(277.7, 36!)</c> is <c>2e-11027</c>. Within
20+
/// them it was a product of k factors, which for <c>binomial(-1/2, 10^12)</c> never reach 0. Found by
21+
/// compilesweep; no issue was filed. The values are mpmath's at 30 digits, to 20.
22+
/// </summary>
23+
[Trait("Area", "Compilation")]
24+
public sealed class ACompiledBinomialOfALargeWholeOrderTest
25+
{
26+
[Theory]
27+
[InlineData(-2.5, 1e20, 7.5225277806367504928e+29)]
28+
[InlineData(277.7, 1e20, 0)]
29+
[InlineData(277.7, 3.7199332678990125e41, 0)]
30+
[InlineData(-0.5, 1e12, 5.6418958354768576325e-7)]
31+
[InlineData(-0.5, 1e12 + 1, -5.6418958354740366846e-7)]
32+
[InlineData(3.25, 2e6, 3.0992465282944267377e-27)]
33+
[InlineData(-7.5, 1e7 + 1, -1.6899292703910971418e+42)]
34+
// A whole n at least 0 below k has nothing to choose, and nor has a negative k.
35+
[InlineData(5, 1e20, 0)]
36+
[InlineData(-2.5, -1e20, 0)]
37+
public void IsItsValue(double n, double k, double expected)
38+
{
39+
var real = "binomial(x, y)".ToEntity().Compile<double, double, double>("x", "y");
40+
var fast = "binomial(x, y)".ToEntity().Compile("x", "y");
41+
var linq = "binomial(x, y)".ToEntity().Compile<Complex, Complex, Complex>("x", "y");
42+
var task = Task.Run(() => (real(n, k), fast.Call(n, k), linq(n, k)));
43+
Assert.True(task.Wait(TimeSpan.FromSeconds(30)), $"binomial({n}, {k}) did not finish");
44+
var (overDouble, byFast, byLinq) = task.Result;
45+
Assert.True(Close(expected, overDouble), $"binomial({n}, {k}) over double is {overDouble}");
46+
Assert.True(Close(expected, byFast.Real) && byFast.Imaginary == 0, $"binomial({n}, {k}) by FastExpression is {byFast}");
47+
Assert.True(Close(expected, byLinq.Real) && byLinq.Imaginary == 0, $"binomial({n}, {k}) by LINQ is {byLinq}");
48+
}
49+
50+
[Fact]
51+
public void AComplexUpperArgumentIsItsValue()
52+
{
53+
var value = "binomial(x, y)".ToEntity().Compile("x", "y").Call(new Complex(0.5, 1), 1e7);
54+
var expected = new Complex(6.5666206043323881952e-11, -1.7327461680588210534e-11);
55+
Assert.True((value - expected).Magnitude < 1e-12 * expected.Magnitude, $"binomial(1/2 + i, 10^7) is {value}");
56+
}
57+
58+
private static bool Close(double expected, double actual)
59+
=> expected == 0 ? actual == 0 : Math.Abs(actual - expected) < 1e-12 * Math.Abs(expected);
60+
}
61+
}

0 commit comments

Comments
 (0)