Repository navigation
Conversation
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
|
Warning Review limit reachedYou'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. View limit details
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. |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 176 |
| Duplication | -2 |
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.
This was referenced Dec 2, 2026
This was referenced Dec 2, 2026
ondrik
force-pushed
the
review/fix-int-backend
branch
from
December 2, 2026 13:16
18ab096 to
b9814c5
Compare
ondrik
force-pushed
the
review/fix-approx
branch
from
December 2, 2026 13:16
b42e5e0 to
431ce7c
Compare
ondrik
marked this pull request as ready for review
December 2, 2026 13:58
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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(),Intervalarithmetic and the conversion fromBigIntto double. It is based on the previous PR in the stack, branchreview/fix-int-backend, so the diff shows only these 3 commits. Please review and merge the PRs in stack order.mainThe 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
to_intervaldoes not enclose the exact value #7: the root enclosures into_interval()allowed for libm's error but not for the rounding of the angle pi*j/n. SoRe(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 newdetail::root_table(n)inapprox.hppreduces 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).Interval::operator*:0 · ±∞poisons the interval with NaN #13:Interval::operator*returned[NaN, NaN]when a bound product was0 * inf. Now a bound product with a zero factor is 0. The exact zero roots from [C2]to_intervaldoes not enclose the exact value #7 make0 * infreachable fromto_interval(), so both fixes are in the same commit (8972431).to_complex/to_intervalapply √2^−k separately from the coefficients #20:to_complex()multiplied the sum bypow(1/sqrt2, k), andto_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 sumc_j * 2^-shiftand apply2^(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).BigInt::to_doubletruncates #35:BigInt::to_double()usedmpz_get_d, which truncates, so 2^54 + 3 converted differently with BigInt than withChecked<i64>. It now rounds to nearest, ties to even, without allocating (1b39239).ACN_SCALE_EXP_64: negating k = INT64_MIN #37 (closed in the acn-arith PR): the new scaling computesq = k >> 1and never negates k. It is tested at the minimum k with both the 32-bit and the 64-bitScaleExp.Behaviour changes
to_complex(i) == (0, 1)andoperator<<prints~0+1i.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 whereldexpleaves 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()andto_interval()raisestd::invalid_argumentfor a precision that is not a power of two.acn/approx.hpp(included byacn.hpp) with the shareddetail::code, andBigInt::to_double_2exp(), which rounds wherempz_get_d_2exptruncates.BigInt::bit_length()is now computed inline from the top limb.interval_detail::interval_pow,interval_detail::sqrt2_power_intervalandinterval_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 callsqrt2_power_interval. Without that line, both enclose the exact values.review/fix-guarantees, 222617e) keeps tables only up to n = 2^16 and computes larger roots per term.test_intervalnow linksThreads::Threads.test_interval_mpfris built only when MPFR is found, and CI installslibmpfr-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
cosandsinare 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 (kRootUlpMargininapprox.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 infirst_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-overflowinmatrix.hppthat GCC 13.4 (used locally) does not. Commit 3d9ece0 in #58 fixes it by makingAcn(),zero(),one()andcoeff_span()constexpr; the later #42 commit in #69 made themconstexpranyway, 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=ONand built with 0 warnings. MPFR was found, sotest_interval_mpfrran. No log containsNo test cases matched,in 0 test casesorNo tests ran.review/fix-int-backend)ACN_WITH_GMP=OFF-O1)clang++ was not run locally. It runs in CI: the existing {g++, clang++} × {Debug, Release} × GMP matrix.
New tests:
to_intervaldoes not enclose the exact value #7:test_intervaltests 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, thatto_complexuses 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 astd::latch, and a failed thread start joins the started threads. Also new:test_interval_mpfr, a randomized check ofto_intervalagainst MPFR forAcn<N, CheckedI64>,AcnDyn<CheckedI64>andAcn<N, BigInt>with huge coefficients and k. It requiresto_complex(0)to be exactly 0 and checkszero()at each precision.Interval::operator*:0 · ±∞poisons the interval with NaN #13:Intervalmultiplication takes0 * infas 0, andto_intervalof a BigInt value at k = 2148 (the issue's MWE) has no NaN bound.to_complex/to_intervalapply √2^−k separately from the coefficients #20:test_intervaltests that 1/sqrt2^2000 is scaled exactly, that aChecked<i64>value nearDBL_MAXgives finite results, and BigInt values with coefficients beyondDBL_MAX. The 2^1025 reference is computed as 2^1025 / (239 + 169 sqrt2), so it does not overflow wherelong doubleis binary64.test_scale_expandtest_scale_exp64check saturation at both ends ofScaleExp(this also covers [L11]ACN_SCALE_EXP_64: negating k = INT64_MIN #37).test_bigintchecksbit_length().BigInt::to_doubletruncates #35:test_biginttests rounding to nearest likeChecked<i64>, ties to even beyond i64, overflow to inf, andto_double_2exp. A differential test checks thatto_complex/to_intervalagree between BigInt andChecked<i64>; it covers the issue's MWE and 500 random values.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