Skip to content

fix(approx): sound roots, Interval 0*inf, scale last, BigInt::to_double - #62

Open
ondrik wants to merge 3 commits into
review/fix-int-backendfrom
review/fix-approx
Open

ondrik wants to merge 3 commits into
review/fix-int-backendfrom
review/fix-approx

Conversation

@ondrik

@ondrik ondrik commented Dec 2, 2026 •

Copy link
Copy Markdown

This is part 5 of 13 of the split of #56, which fixes the code review findings tracked in #5. It covers to_complex(), to_interval(), Interval arithmetic and the conversion from BigInt to double. It is based on the previous PR in the stack, branch review/fix-int-backend, so the diff shows only these 3 commits. Please review and merge the PRs in stack order.

# PR Base Fixes
1 #58 main #6, #10, #18, #27
2 #59 #58 #14, #15, #17, #32, #37
3 #60 #59 #8, #9, #23, #29, #30, #33
4 #61 #60 #22, #39
5 #62 (this PR) #61 #7, #13, #20, #35
6 #63 #62 #11, #12, #19, #21, #34
7 #64 #63 #16, #36
8 #65 #64 #28
9 #66 #65 #31
10 #67 #66 #24, #26, #38
11 #68 #67 #25, #41
12 #69 #68 #40, #42
13 #70 #69 follow-ups only

The performance PRs for #43–#55 are stacked on top of #70: #71, #72, #73, #74, #75, #76, #77, #78, #79.

How to merge this stack: see the merge guide (one at a time, in order, with "Create a merge commit", then delete the merged branch so the next PR retargets to main).

Issues

  • Fixes [C2] to_interval does not enclose the exact value #7: the root enclosures in to_interval() allowed for libm's error but not for the rounding of the angle pi*j/n. So Re(i) came out as [6.1e-17, 6.1e-17], a large i-coefficient could flip the sign of Re, and for n >= 16 more roots fell outside their margin. The new detail::root_table(n) in approx.hpp reduces each angle exactly, in integer arithmetic, to the first octant. The roots 1 and i are then exact and pi/4 is the correctly rounded sqrt2/2; the remaining libm values are widened by 4 ulps, a margin derived in the header. to_complex() uses the same roots (8972431).
  • Fixes [H6] Interval::operator*: 0 · ±∞ poisons the interval with NaN #13: Interval::operator* returned [NaN, NaN] when a bound product was 0 * inf. Now a bound product with a zero factor is 0. The exact zero roots from [C2] to_interval does not enclose the exact value #7 make 0 * inf reachable from to_interval(), so both fixes are in the same commit (8972431).
  • Fixes [M7] to_complex/to_interval apply √2^−k separately from the coefficients #20: to_complex() multiplied the sum by pow(1/sqrt2, k), and to_interval() multiplied it by an interval power of sqrt2. Either factor alone could leave the double range, so values of moderate size came out as NaN, [-inf, inf] or 0, or 800 ulps off. Both functions now sum c_j * 2^-shift and apply 2^(shift - q) * (1/sqrt2)^r, with k = 2q + r, once at the end. Values outside the double range saturate to ±inf or 0, and the intervals stay sound (431ce7c).
  • Fixes [L9] BigInt::to_double truncates #35: BigInt::to_double() used mpz_get_d, which truncates, so 2^54 + 3 converted differently with BigInt than with Checked<i64>. It now rounds to nearest, ties to even, without allocating (1b39239).
  • Refs [L11] ACN_SCALE_EXP_64: negating k = INT64_MIN #37 (closed in the acn-arith PR): the new scaling computes q = k >> 1 and never negates k. It is tested at the minimum k with both the 32-bit and the 64-bit ScaleExp.

Behaviour changes

  • The roots 1 and i are exact, so to_complex(i) == (0, 1) and operator<< prints ~0+1i.
  • Values beyond the double range saturate. to_complex() gives ±inf or 0. to_interval() gives bounds such as [DBL_MAX, inf] or [0, 4.9e-324]. It steps a bound outward only where ldexp leaves the normal range, and never across 0.
  • BigInt::to_double() rounds to nearest; it used to truncate. Beyond the double range it gives ±inf.
  • to_complex() and to_interval() raise std::invalid_argument for a precision that is not a power of two.
  • New: header acn/approx.hpp (included by acn.hpp) with the shared detail:: code, and BigInt::to_double_2exp(), which rounds where mpz_get_d_2exp truncates. BigInt::bit_length() is now computed inline from the top limb.
  • Removed: interval_detail::interval_pow, interval_detail::sqrt2_power_interval and interval_detail::kLibmUlpMargin. The MWEs of [H6] Interval::operator*: 0 · ±∞ poisons the interval with NaN #13 and [L11] ACN_SCALE_EXP_64: negating k = INT64_MIN #37 call sqrt2_power_interval. Without that line, both enclose the exact values.
  • Each root table is built on the first use of its precision n, published with a compare-and-swap, shared by all threads and never freed. In this PR, a table is kept for every precision that gets used, at 48 bytes per root (768 MiB at n = 2^24). The last PR in the stack (review/fix-guarantees, 222617e) keeps tables only up to n = 2^16 and computes larger roots per term.
  • test_interval now links Threads::Threads. test_interval_mpfr is built only when MPFR is found, and CI installs libmpfr-dev.

Decisions for @MichalHe

This is decision 10 from #56. Please confirm it or reject it.

10. Soundness of the interval roots. The enclosures assume that libm's cos and sin are within 1 ulp on [0, pi/4]. This holds for glibc, musl and Apple's libm, but the C++ standard sets no bound. Given that assumption, the 4-ulp margin (kRootUlpMargin in approx.hpp) is derived in the header comment. Root tables are never freed; this PR keeps one for every precision used, and the guarantees PR limits that to n <= 2^16.

The alternative is not to rely on libm's accuracy. That means a wider margin or roots from another source. To change this, change 8972431: the margin and its derivation are in approx.hpp, and the roots are computed in first_octant_root. 1b39239 and 431ce7c do not depend on this choice.

Testing

The first CI run failed in the g++ Release jobs: GCC 13.3, the g++ of the ubuntu-24.04 runners, reports a false -Wstringop-overflow in matrix.hpp that GCC 13.4 (used locally) does not. Commit 3d9ece0 in #58 fixes it by making Acn(), zero(), one() and coeff_span() constexpr; the later #42 commit in #69 made them constexpr anyway, so the tree after #69 is unchanged. The local results below were taken before that change. After it, this tip was rebuilt and tested again with g++-13 Release -DACN_WERROR=ON: 234/234 passed, 0 warnings, and CI runs the full matrix.

Run locally on the branch tip tree (835a7e4). Each configuration used -G Ninja -DACN_WERROR=ON and built with 0 warnings. MPFR was found, so test_interval_mpfr ran. No log contains No test cases matched, in 0 test cases or No tests ran.

Configuration Result (base review/fix-int-backend)
g++ 15.2 Debug 234/234 (213)
g++ 13.4 Debug 234/234 (213)
g++ 13.4 Release 234/234 (213)
g++ 13.4 Release, ACN_WITH_GMP=OFF 197/197 (184)
g++ 13.4 ASan+UBSan (Debug, -O1) 234/234 (213)

clang++ was not run locally. It runs in CI: the existing {g++, clang++} × {Debug, Release} × GMP matrix.

New tests:

  • [C2] to_interval does not enclose the exact value #7: test_interval tests that Re of a multiple of i contains 0, that the sign of Re next to a large i-coefficient is right, that roots whose angle rounding exceeded the old margin are enclosed, that to_complex uses exact 1 and i, and that threads using a precision for the first time get the same result. In the last test, the workers start together on a std::latch, and a failed thread start joins the started threads. Also new: test_interval_mpfr, a randomized check of to_interval against MPFR for Acn<N, CheckedI64>, AcnDyn<CheckedI64> and Acn<N, BigInt> with huge coefficients and k. It requires to_complex(0) to be exactly 0 and checks zero() at each precision.
  • [H6] Interval::operator*: 0 · ±∞ poisons the interval with NaN #13: Interval multiplication takes 0 * inf as 0, and to_interval of a BigInt value at k = 2148 (the issue's MWE) has no NaN bound.
  • [M7] to_complex/to_interval apply √2^−k separately from the coefficients #20: test_interval tests that 1/sqrt2^2000 is scaled exactly, that a Checked<i64> value near DBL_MAX gives finite results, and BigInt values with coefficients beyond DBL_MAX. The 2^1025 reference is computed as 2^1025 / (239 + 169 sqrt2), so it does not overflow where long double is binary64. test_scale_exp and test_scale_exp64 check saturation at both ends of ScaleExp (this also covers [L11] ACN_SCALE_EXP_64: negating k = INT64_MIN #37). test_bigint checks bit_length().
  • [L9] BigInt::to_double truncates #35: test_bigint tests rounding to nearest like Checked<i64>, ties to even beyond i64, overflow to inf, and to_double_2exp. A differential test checks that to_complex/to_interval agree between BigInt and Checked<i64>; it covers the issue's MWE and 500 random values.
  • A test that rejects precisions that are not a power of two.

According to #56, the tests for the critical and high issues (#7 and #13 here) were checked to fail in Release with the fix reverted.

Earlier review discussion (CodeRabbit, Codacy) is on #56.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92

ondrik and others added 3 commits December 2, 2026 11:55
to_interval() enclosed cos/sin(fl(pi*j/n)) with a 4-ulp margin that
covers libm's error but not the rounding of the angle itself, which
dominates where cos or sin is small: Re(i) came out as
[6.1e-17, 6.1e-17], a large i-coefficient could flip the sign of Re, and
for n >= 16 more roots were off by more than the margin.

detail::root_table(n) (new approx.hpp) reduces pi*j/n exactly, in
integer arithmetic, to the first octant: the roots 1 and i are exact,
pi/4 is the correctly rounded sqrt2/2, and the rest are libm's cos/sin
of the reduced angle widened by 4 ulps. The header derives that bound
(argument rounding plus a libm error of 1 ulp). Each table is built once
per n, published with a compare-and-swap and shared by all threads.
to_complex() uses the same roots, so Re(i) is exactly 0 there too. A
precision that is not a power of two now raises std::invalid_argument
in to_complex() and to_interval().

Interval::operator* took the min/max of the four bound products, and a
0 * inf product is NaN: when it came first, the result was [NaN, NaN].
A bound product with a zero factor is now 0. The exact zero roots make
0 * inf reachable from to_interval, so the two fixes ship together.

Tests: the MWEs of both issues, and a randomized check against MPFR
(test_interval_mpfr, built only when MPFR is found; CI installs
libmpfr-dev).

The concurrent root-table test starts its workers together on a
std::latch, so the publication race is exercised, and joins the started
threads if a later one fails to start.

Fixes #7.
Fixes #13.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
BigInt::to_double() used mpz_get_d, which truncates, while
Checked<Word>::to_double() rounds to nearest, so the same value gave
different to_complex() results by backend: 2^54 + 3 became ...984 with
BigInt and ...988 with Checked<i64>. It now rounds to nearest, ties to
even, without allocating: the top 128 bits of the magnitude, read from
the limbs with any lower nonzero bit folded in as a sticky bit, go
through the conversion from unsigned __int128, which rounds to nearest.
Values beyond the double range give +-inf, as IEEE rounding does. The
rounded mantissa and exponent are also available as to_double_2exp(),
the rounding counterpart of mpz_get_d_2exp.

Fixes #35.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
to_complex() summed c_j.to_double() * omega^j and multiplied the sum by
pow(1/sqrt2, k); to_interval() multiplied by an interval power of
sqrt2. Either factor alone can leave the double range for a value of
moderate size: (2^1100 + 1)/sqrt2^2200 ~ 1 came out as NaN and
[-inf, inf], (2^1000 + 1)/sqrt2^2160 ~ 8.3e-25 as 0, a Checked<i64>
value of 7.5e305 as inf, and 1/sqrt2^2000 = 2^-1000 800 ulps off.

Both now sum the coefficients scaled by 2^-shift, where shift is 0
unless a BigInt coefficient is wider than 960 bits (then each
coefficient comes from BigInt::to_double_2exp), and apply
2^(shift - q) * (1/sqrt2)^r, k = 2q + r, at the end: one ldexp and at
most one multiply by the correctly rounded 1/sqrt2. q = k >> 1 never
negates k. to_interval steps a bound outward only where the ldexp
leaves the normal range, never across 0, so it stays sound: a value
beyond the double range gives e.g. [DBL_MAX, inf] or [0, 4.9e-324],
and to_complex gives +-inf or 0. The shared code is
detail::approximate() and its helpers in approx.hpp, which replace
interval_detail::interval_pow and sqrt2_power_interval.
BigInt::bit_length(), now called once per coefficient, is computed
inline from the top limb.

The MPFR comparison requires to_complex(0) to be exactly 0 and checks
zero() at each precision, and the 2^1025 reference is computed as 2^1025
/ (239 + 169 sqrt2), which neither overflows nor cancels where long
double is binary64.

Fixes #20.
Refs #37.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LX2x8TzXgZCE8xUyBZSW92
@coderabbitai

coderabbitai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 18 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b88f29d0-2494-44de-b8c0-331daaef8fe4
Commits

Reviewing files that changed from the base of the PR and between b9814c5 and 431ce7c.

Files selected for processing: 12

  • .github/workflows/ci.yml
  • include/acn/acn.hpp
  • include/acn/acn_dynamic.hpp
  • include/acn/acn_static.hpp
  • include/acn/approx.hpp
  • include/acn/bigint.hpp
  • include/acn/interval.hpp
  • tests/CMakeLists.txt
  • tests/test_bigint.cpp
  • tests/test_interval.cpp
  • tests/test_interval_mpfr.cpp
  • tests/test_scale_exp.cpp
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@codacy-production

codacy-production Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 176 complexity · -2 duplication

Metric Results
Complexity 176
Duplication -2

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

@ondrik
ondrik force-pushed the review/fix-int-backend branch from 18ab096 to b9814c5 Compare December 2, 2026 13:16
@ondrik
ondrik force-pushed the review/fix-approx branch from b42e5e0 to 431ce7c Compare December 2, 2026 13:16
@ondrik
ondrik marked this pull request as ready for review December 2, 2026 13:58
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.

1 participant