# Math and numeric utility completion Status: planning only; all tasks are **PLANNED**. Source baseline: `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`, inspected 2026-11-24. ## Current capabilities [Math](../../../src/Math/module.cmake) declares no dependencies. [Numeric](../../../include/Void/Math/Numeric.hpp) provides `Void::Numeric::Error`, checked, saturating and unsigned wrapping arithmetic, parsing, range and narrowing helpers. Checked arithmetic currently uses compiler overflow builtins. `parse_int`/`parse_double` pass `string_view::data()` to C conversion functions, so a bounded non-NUL-terminated substring requires correction. The `long long`-based narrowing interface is insufficient for every unsigned conversion. These are concrete foundations work, not scientific scope. [Random](../../../include/Void/Math/Random.hpp) implements `Void::Random::Xoshiro256`, a thread-local generator, distributions, shuffle and sampling. Sampling materializes all `n` indices; `k > n` is not explicitly rejected. The generator is for simulations, sampling and jitter, not secrets. [Histogram](../../../include/Void/Math/Histogram.hpp) contains keyed frequency and fixed-bin structures. Fixed-size arithmetic exists in [Matrix](../../../include/Void/Math/Matrix.hpp) under `Void::Matrix` and [Vec](../../../include/Void/Math/Vec.hpp)/[Mat](../../../include/Void/Math/Mat.hpp) under `Void::Math`. Their distinct Mat4 names must not be silently treated as aliases. [Numeric](../../../tests/standalone/Math/Numeric.cpp), [Random](../../../tests/standalone/Math/Random.cpp), [Histogram](../../../tests/standalone/Math/Histogram.cpp), [Matrix](../../../tests/standalone/Math/Matrix.cpp), and [VecMat](../../../tests/standalone/Math/VecMat.cpp) suites are current regression sources. Graph parsing is partial at Mat line 15 and Vec lines 13/50/91; these template declarations were read directly. No build or benchmark result is inferred from source inspection. ## Target and backend decisions Keep standard-library-only, native numeric utilities below Data and application modules, per [C-01/C-02](../ARCHITECTURE.md). Core UUID removes its Math include; Math must not depend back on Data to supply numeric conversion. Functional provides optional enum-to- Error adapters, not a required string allocation in every arithmetic operation. Math imports neither Containers nor Algorithms; fixed arrays and standard-library scratch storage keep its scalar arithmetic below both. M-MATH-02 supplies the narrow checked- arithmetic prerequisite for Algorithms before Containers/Text adapters depend on it. Standard `from_chars`, distributions and ranges remain the default tools; overflow builtins are guarded optimizations over a constexpr portable reference path. No BLAS, Eigen, arbitrary precision or general scientific platform is introduced by this plan. ## NEW conversion and arithmetic APIs Illustrative NEW additions in `include/Void/Math/Numeric.hpp`: ```cpp namespace Void::Numeric { enum class Rounding { exact, toward_zero, nearest_even }; template std::expected checked_cast(From value, Rounding mode = Rounding::exact) noexcept; template std::expected parse_integer(std::string_view, int base = 10) noexcept; template std::expected parse_real(std::string_view) noexcept; template std::expected checked_mul_add(T a, T b, T c) noexcept; } ``` Integer-to-integer conversion compares ranges by signedness without first narrowing. Float-to-integer first rejects NaN/infinity, then applies the named rounding policy, then tests against exactly representable exclusive/inclusive bounds before casting. Default exact rejects fractional values. Integer-to-float exact rejects a value if its significand cannot be represented; the implementation checks significant bits instead of performing an unsafe float-to-integer round trip. Float narrowing exact rejects loss of finite value; explicit nearest-even uses the documented floating environment policy. `Error` gains `Inexact` and `NonFinite` in the major release. Data converts these domain errors into path-aware diagnostics without changing Numeric's low-cost enum. Parsing consumes precisely the supplied span and requires full token consumption. Integer bases are 2–36; base autodetection is a separate named policy, not default. No locale whitespace, leading plus, partial suffix, or nonfinite token is accepted by the default parser. Maximum numeric token is 256 bytes; an explicit larger bounded policy is separate. Grammar validation precedes conversion; there is no NUL scan beyond input. `checked_mul_add` is specified as sequential checked multiplication then addition, so an overflowing intermediate fails even if cancellation could produce a final in-range mathematical result. Saturating helpers use these classifications deliberately; wrapping arithmetic remains unsigned-only. Resource-size checked add/multiply stays available without a dependency on dynamic matrix or random headers. ## Other capability backlogs Random adds injected-URBG overloads for distributions, shuffle and sampling, leaving thread-local convenience APIs as adapters. Seeded Xoshiro output has fixed golden vectors; standard-distribution output is not promised identical across standard-library vendors. Defaults cap sample output at 1,048,576 elements and scratch at 16 MiB. Reject `k > n`. Use Floyd sampling for sparse `k` (O(k) memory), and partial Fisher–Yates for dense samples only within the scratch cap; the selection threshold is `k <= n/8`, frozen with tests. No unrequested entropy acquisition occurs when a generator is supplied. Histogram adds bounded merge, count-overflow errors and deterministic tie-breaking. Keyed defaults cap at 65,536 distinct keys; fixed bins default to 1,024 with maximum 65,536, finite ordered endpoints and explicit underflow/overflow counters. NaN is rejected. Quantiles from fixed bins are approximate intervals, not invented exact percentiles; Time's exact benchmark samples do not reuse approximate results unnoticed. Matrix work retains stack storage for fixed sizes, adds checked normalization/inversion with singular/nonfinite diagnostics, and documents row-major layout and transformation conventions. Select `Void::Matrix::Matrix` as the shared arithmetic kernel while keeping Vec named-field value types and `Void::Math::Mat4` facades. Conversion is explicit until a major-version ABI change; no reinterpret-cast view assumes matching layouts. No heap-sized dynamic matrix is included. Generic integer matrix operations get checked variants rather than promising undefined signed overflow is acceptable. ## Task DAG | Task | Phase; dependencies | Scope and acceptance | Recommended role | | --- | --- | --- | --- | | M-MATH-01 | P0; current source | Capture existing numeric, generator and matrix fixtures and namespace/layout contracts; identify builtins and unsupported conversion edges. | sol_implementer | | M-MATH-02 | P1; M-MATH-01 | Implement span-safe parsers, checked_cast and portable overflow fallback; signed/unsigned and float boundaries pass without undefined behavior. | astra_implementer | | M-MATH-03 | P2; M-MATH-02 | Add injected RNGs and bounded sampling; k=0/k=n/k>n, huge n with small k and seeded generator vectors pass within scratch limits. | sol_implementer | | M-MATH-04 | P2; M-MATH-02 | Complete bounded histograms and merge semantics; count overflow leaves prior histogram intact and approximate outputs carry bounds. | sol_implementer | | M-MATH-05 | P2; M-MATH-02 | Consolidate matrix arithmetic kernel with explicit facade conversion; singular/zero-vector, row-major and integer-overflow tests pass. | sol_implementer | | M-MATH-06 | P3; M-MATH-03–05 | Benchmark targeted kernels, publish compatibility adapters and isolated installed consumers; optional vectorization is admitted only after scalar differential tests. | sol_implementer | ## Limits, verification and migration All operations are synchronous and caller-owned; no queue, cancellation thread or shutdown service exists. Batch sampling/merging receives a stop token only in explicit long-running overloads, checked at bounded chunks, returning no partially published output. Matrix template extents are compile-time; recommended instantiated extents are at most 16×16 until compiler/build-cost evidence supports larger values. This is a supported profile, not a claim that all larger templates cannot compile. CURRENT tests are the linked suites; no new execution was performed. PROPOSED validation uses property tests against wide/reference arithmetic, bounded substrings adjacent to guard pages, all small integer widths, INT64_MIN/UINT64_MAX, 2^53±1, fractional edges, NaN/infinities, subnormals and negative zero. Differential RNG tests check range and deterministic engine vectors; statistical smoke tests do not establish cryptographic quality. Matrix residual tests use stated tolerance and scale, not exact floating equality. Follow [PERFORMANCE](../PERFORMANCE.md) for scalar/batch parse throughput, conversion p50/p95/p99, sample allocations/RSS/CPU and header/template build cost. Separate entropy, engine and distribution costs. [VALIDATION](../VALIDATION.md) and [BUILD-AND-DISTRIBUTION](../BUILD-AND-DISTRIBUTION.md) own future commands/toolchains. [Migration](../MIGRATION.md) deprecates unsafe `long long` narrowing wrappers and preserves legacy parsing only through named adapters. Exact Data integer conversion is gated on M-MATH-02 and does not change StrictJson. Old Mat4 storage/ABI remains until a major break; rollback selects the old package with no persisted numeric conversion. Consumers must not persist native object representations as wire formats; [Binary](Binary.md) owns those. See [requirements](../REQUIREMENTS.md), [dependencies](../DEPENDENCIES.md), [delivery](../DELIVERY.md) and [Data](Data.md).