Skip to content

Fix catastrophic cancellation in ibeta_inv_imp for a == 1, b == 1 - #1676

Closed
3956418278-dotcom wants to merge 1 commit into
boostorg:developfrom
3956418278-dotcom:fix/ibeta-inv-a1-b1-complement
Closed

3956418278-dotcom wants to merge 1 commit into
boostorg:developfrom
3956418278-dotcom:fix/ibeta-inv-a1-b1-complement

Conversation

@3956418278-dotcom

Copy link
Copy Markdown

Problem

In include/boost/math/special_functions/detail/ibeta_inverse.hpp, the trivial a == 1 && b == 1 fast path in ibeta_inv_imp currently sets *py = 1 - p instead of *py = q:

else if(a == 1)
{
   if(b == 1)
   {
      if(py) *py = 1 - p;
      return p;
   }

When invoked through ibetac_inv(1, 1, q, &y) (where p = 1 - q is already passed alongside exact q), computing 1 - p = 1 - (1 - q) suffers catastrophic cancellation for small q and underflows to 0 below q ~ 1.11e-16.

This directly affects quantile(complement(fisher_f_distribution<double>(2, 2), q)), which evaluates df2 * x / (df1 * y) = x / y (exact closed form: (1 - q) / q):

q Before After Exact (1 - q) / q
1e-7 9999999.0052635577 9999999.0000000019 9999999
1e-10 9999999171.5963593 9999999999 9999999999
1e-15 1000799917193442.5 (rtol = 8.0e-4) 999999999999998.88 999999999999999
3.85e-16 3002399751580329.5 (rtol = 15.6%) 2597402597402596.5 2597402597402596.4...
1e-20 inf 1e+20 1e+20 - 1
1e-300 inf 9.999999999999999e+299 1e+300 - 1

Fix

Assign *py = q directly when a == 1 && b == 1, preserving full precision for both ibeta_inv and ibetac_inv.

Testing

  • Added test_complement_quantile_df2_2 in test/test_fisher_f.cpp covering both quantile(complement(fisher_f_distribution<double>(2, 2), q)) and ibetac_inv(1, 1, q, &y) across q down to 1e-300.
  • Verified locally with standalone C++17 compilation (-DBOOST_MATH_STANDALONE=1) against both ibeta_inv and ibetac_inv.

Discovered while auditing scipy/scipy#26692 / scipy/scipy#26696.

AI disclosure: An AI coding assistant (Antigravity) was used to run the numerical sweep that identified this edge case, verify the fix, and draft this PR description; I reviewed the patch and test results.

@mborland

Copy link
Copy Markdown
Member

Superseded by: #1679. Thanks for bringing this to our attention

@mborland mborland closed this Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants