# bend-float64 IEEE 754 binary64 (`double`, NumPy's `float64`) for Bend 2, in pure Bend. Bend has no 64-bit types, so a float64 is two `U32` words and every operation is integer arithmetic on them. Each result is **correctly rounded** (to nearest, ties to even) and has **the bits x86-64 gives**, NaNs included. 32.5 million random cases were checked bit for bit against NumPy and glibc on x86-64, and the NaN rules are proved for every input. NumPy's float64 math functions are here too, from `exp`, `log` and `sin` to `power` and `hypot`. Every one is correctly rounded, which NumPy and glibc are not everywhere. Each matched mpmath on all 65,536 test inputs. Text goes both ways, as Python's `repr` and `float()` do it: `show` prints the shortest digits that read back to the same float64, and `parse` reads any decimal text, rounding it correctly however many digits it has. ```bend import bend-float64@0.1.3.0/float64.bend as F import bend-float64@0.1.3.0/text.bend as T import bend-float64@0.1.3.0/math.bend as M def sum_text(r: Result<&2, &2, String, F.F64>) -> String: match r: case Done{x}: T.show(F.add(x, F.div(F.from_i32(1), F.from_i32(5)))) case Fail{why}: why def main() -> IO(Unit): do IO: IO.print(sum_text(T.parse("0.1"))) # 0.30000000000000004 IO.print(sum_text(T.parse("1__0"))) # could not convert string to float: '1__0' IO.print(T.show(M.sin(F.of_bits(2146435071, 4294967295)))) # sin(1.7976931348623157e+308): 0.004961954789184062 ``` ## What it has | | | | --- | --- | | type | `F64{hi, lo}`: `hi` holds the sign, the 11-bit exponent and the top 20 fraction bits, `lo` the low 32; `of_bits(hi, lo)`, `hi_bits`, `lo_bits` | | arithmetic | `add`, `sub`, `mul`, `div`, `sqrt`, `fma(a, b, c)` (a * b + c, rounded once) | | sign | `neg`, `abs`, `copysign(x, y)`, `signbit` | | compare | `eq`, `ne`, `lt`, `le`, `gt`, `ge` (IEEE: NaN is unordered, -0.0 == +0.0), `minimum`, `maximum` (NumPy's `np.minimum`, `np.maximum`) | | classify | `is_nan`, `is_inf`, `is_finite` | | to an integer value | `trunc`, `floor`, `ceil`, `rint` (ties to even, as `np.round`), or `round_int(mode, x)` with `RTrunc{}`, `RFloor{}`, `RCeil{}`, `REven{}` | | conversions | `from_i32`, `from_u32` (a `U32` holding the integer), `from_f32` / `from_f32_bits` (exact), `to_f32` / `to_f32_bits` (rounded), `to_i32`, `to_u32` (toward zero) | | constants | `zero(s)`, `inf(s)` with `s` = 0 or 2147483648 (the sign bit), `dnan()` (the default NaN), `quiet(x)` | | math (`math.bend`) | `exp`, `exp2`, `expm1`, `log`, `log2`, `log10`, `log1p`, `sin`, `cos`, `tan`, `arcsin`, `arccos`, `arctan`, `arctan2(y, x)`, `sinh`, `cosh`, `tanh`, `arcsinh`, `arccosh`, `arctanh`, `power(x, y)`, `cbrt`, `hypot(x, y)`: NumPy's float64 set, every result correctly rounded | | text (`text.bend`) | `show(x) -> String`, `parse(text) -> Result<&2, &2, String, F64>` (`Done{x}`, or `Fail{why}` with Python's message), and `shortest(e, m)`, the digits and the point's place behind `show` | ## The exact rules - **Rounding.** Every operation rounds to nearest, ties to even, and handles subnormals in full (no flush to zero). NumPy uses no other mode, and no other mode is provided. - **NaN results** are x86's: - a NaN operand passes through with its quiet bit set; - of two NaNs, the first operand's is returned, as `addsd`, NumPy's scalar path, `np.subtract` and `np.divide` do; - `fma` takes b's NaN, then a's, then c's, as glibc's `fma` does on x86-64, even for `0 * inf + NaN`; - an invalid operation gives the default NaN `0xFFF8000000000000`: `inf - inf`, `0 * inf`, `0 / 0`, `inf / inf`, and the square root of a number below zero; - `sqrt(-0.0)` is `-0.0`; - `neg`, `abs` and `copysign` change only the sign bit, NaN or not. - **NumPy's own `add` and `multiply` are not consistent.** For arrays of 9 or more elements their vector loop swaps the operands, so of two NaNs they return the second. bend-float64 always returns the first. - **`minimum`/`maximum`** pass a NaN through unchanged (not quieted), the first if both are NaN. Otherwise they return the second of two equal values, so `minimum(+0.0, -0.0)` is `-0.0`. These are NumPy's answers. - **`to_i32`** truncates, and NaN and values out of range give -2^31 (x86's "integer indefinite"). - **`to_u32`** follows NumPy's `astype(np.uint32)` on x86-64. It truncates to a signed 64-bit integer and keeps the low 32 bits, so `-1.0` gives 4294967295; NaN and values beyond the 64-bit range give 0. - **`to_f32`** rounds to nearest, ties to even. A NaN keeps the top 22 bits of its payload, quieted. ## Text - **`show`** is Python's `repr`. It prints the fewest digits that read back to the same float64, and of those the nearest. The layout is Python's: an exponent below 1e-4 and from 1e16 up (`1e-05`, `0.0001`, `1000000000000000.0`, `1e+16`). A whole number keeps `.0`, the exponent has at least two digits, and the specials are `-0.0`, `inf`, `-inf` and `nan` (every NaN prints as `nan`). It uses Burger and Dybvig's algorithm on exact big integers. - **`parse`** is Python's `float()`: - an optional sign, digits with an optional point, and an optional exponent; - underscores, but only between digits; - `inf`, `infinity` and `nan` in any case (`-nan` keeps its sign bit); - whitespace around the number, the set `float()` strips; - rounding to nearest, ties to even, at any length: past 800 significant digits the rest only says "nonzero", which decides the same way; - `1e400` gives inf and `1e-400` gives 0.0, as in Python. - Text it refuses gives `Fail{"could not convert string to float: '...'"}`. - One difference: only ASCII digits count, where Python also takes other scripts' digits (`'١٢'`). - Short numbers (at most 15 digits, exponent within ±22) take Clinger's fast path: one correctly rounded multiply or divide. Everything else is exact big-integer arithmetic. ## Math functions - **Every result is correctly rounded**: the exact mathematical value, rounded to nearest with ties to even, for every input. Results are the same on every machine, and need no error bounds in the docs. NumPy and glibc are not correctly rounded everywhere. On the test inputs NumPy's `cbrt` differs in about half the cases, and `arcsinh`, `arccosh`, `sinh`, `tanh` and `log10` in thousands. - **How it gets there (Ziv's strategy on balls).** Each function is evaluated on *balls*: values carrying a rigorous error bound, which every operation widens by everything it drops. If every point of the ball rounds to the same float64, that float64 is the answer. - **The fast path** comes first (`fast.bend`, `fb.bend`). Its balls have a fixed 128-bit mantissa and an error count in units of the last place; there are no lists, only native word operations. - It uses tables generated with mpmath (`fbconsts.bend`, from `test/gen_fast.py`): 2^(j/64) for exp, reciprocals and their logarithms for log, atan(j/16) for atan. - Its polynomials have literal coefficients, and each adds its own truncation bound, computed by the generator. - It decides on nearly every ordinary input. Huge trigonometric arguments (from 2^30), inputs near a hard case, and arguments whose ball fails (for example under heavy cancellation) go on to the slow path. - **The slow path** (`ball.bend`) uses big-integer balls. It starts at 128 bits and doubles the precision (256, 512, 1024, 2048) until the ball decides. - Range reductions are exact. On the slow path, `sin`, `cos` and `tan` use 3600 bits of 2/π, so `sin(1e300)` is right; the fast path splits π/2 into three parts. `exp` takes out powers of two, and `log` splits off the exponent. - Division and square root use Newton's method on both paths, with the exact residual bounding the error. - **Exact and halfway answers** can never be settled by refining a ball, so they are found first and computed exactly: - `cbrt` and `hypot` always are: an integer cube or square root with its remainder. - `exp2` of an integer, `log2` of a power of two, and `log10` of 10^0 to 10^22. - In `power`: x a power of two, y an integer up to 64, or y an odd multiple of 2^-j (j ≤ 5) with x's odd part a perfect 2^j-th power. - **Special values** follow C99's Annex F, as NumPy does. NaN bits are NumPy's on x86-64: - a NaN passes through quieted, except that `tanh` gives the plain `0x7FF8000000000000`; - an invalid input gives `0xFFF8...`, except that `log10`, `arcsin` and `arccos` give `0x7FF8...`; - `arctan2` takes x's NaN before y's; - `power(NaN, y)` clears the NaN's sign when y is an odd integer; - `hypot` returns inf when the other operand is a quiet NaN, but quiets a signalling NaN. - **Speed**: on one thread, per call, on ordinary arguments (`test/math_bench.bend`, which includes making each argument). The slow path alone is shown for comparison: | function | fast path first (µs) | slow path only (µs) | | --- | --- | --- | | `exp`, `expm1` | 13 | 90 | | `log`, `log1p` | 14 | 190–200 | | `sin`, `cos` | 14 | 235 | | `tan` | 24 | 358 | | `arcsin`, `arccos` | 30–33 | 390 | | `arctan`, `arctan2` | 21–24 | 340–380 | | `sinh`, `cosh`, `tanh` | 17 | 135–140 | | `arcsinh`, `arccosh`, `arctanh` | 16–25 | 235–255 | | `power` | 19 | 370 | That is 7–19 times faster. glibc takes tens of nanoseconds; these functions are for programs that need the same bits everywhere, not for bulk arrays. `hypot` (25 µs) and `cbrt` are exact integer roots and did not change. ## How it is checked - `LAWS.bend` / `PROOF.bend` hold the arithmetic's 20 laws, gated by `./bend-check PROOF.bend --verdict`. - The NaN rules above are proved for **every** input: first and second operand for add, sub, mul and div; the order b, a, c for fma; sqrt and the four roundings; all six comparisons; minimum and maximum. - Correct rounding is pinned at about 90 literal inputs, each chosen to exercise a rounding path: ties, overflow thresholds, gradual underflow, exact cancellation, the sign of zero, fma's single rounding, and conversion edges. Every expected value comes from the hardware. - `TEXT_LAWS.bend` / `TEXT_PROOF.bend` hold the text's 4 laws, gated by `./bend-check TEXT_PROOF.bend --verdict`. It is a separate gate so that each file stays within the checker's 10-second limit. The laws are literal: repr's layout on both sides of each switch, shortest digits (1e+23 needs the even-boundary rule), Python's values for signs, whitespace, underscores, inf and nan, halfway ties through both conversion paths, and ten refused texts with their messages. - `MATH_LAWS.bend` / `MATH_PROOF.bend` (7 laws) and `POWER_LAWS.bend` / `POWER_PROOF.bend` (2) cover the math functions. They are gated by `./bend-check MATH_PROOF.bend --verdict` and `./bend-check POWER_PROOF.bend --verdict`, two files so that each stays within the checker's limit. - For every input, a NaN passes through the 20 one-argument functions as NumPy passes it. `arctan2` takes x's NaN, then y's. - At literal inputs: 21 special values; 14 exact answers (including exp2(-1075), halfway to 0, rounding to 0); power's C99 table, 15 entries; arctan2's signed zeros. The ball evaluations themselves are too slow for the checker, so their correctness rests on the tests. The fast path is out of reach too: the formal kernel behind `--verdict` runs out of fuel evaluating even `exp(1)`. Its own tests and mutants are below. - `mutants.sh` plants 55 single bugs, and the laws catch all 55. - 27 are in the arithmetic: ties rounding up, a lost sticky bit, a lost carry, a NaN that is not quieted, and others. - 12 are in the text: the layout switch moved, the exponent's padding lost, a boundary taken whatever the significand's parity, a trailing underscore accepted, halfway text rounding up, and others. - 16 are in the math functions: a NaN not quieted, the wrong NaN first, an exact path off by a power of two, a C99 table entry wrong, and others. - `test/check.py` runs `test/cases`, a Bend program that prints random cases of all 31 operations. It recomputes each case with NumPy and glibc's `fma` on the machine and compares the bits. - The inputs mix special values, subnormals, both ends of the exponent range, sparse and dense significands, exact ties, and pairs close enough to cancel. - `python3 check.py 20` runs 2^20 cases per operation, 32.5 million in all; every one matched on x86-64. - `test/text_check.py` checks the text in both directions. For `show`, 2^20 random float64s were printed, and every one equals Python's `repr`. For `parse`, a million strings were read, and every one gives `float()`'s bits or is refused as `float()` refuses it. The strings include exact halfway points between neighbouring floats and the values just either side, texts past 800 digits, both thresholds, whitespace, underscores and malformed text. - `test/math_check.py` compares the math functions with mpmath on 65,536 inputs per function, 1,507,328 in all, and every one is correctly rounded. Values are computed at 300 bits, at 600 when the two disagree, and rounded through an exact fraction, so subnormal results round once. Special and NaN results are compared with NumPy's bits. The inputs mix the general set above with each function's own hard cases: arguments near 1 for the logs, near multiples of π/2 for the trigonometry, near ±1 for arcsin and arctanh, perfect powers, cubes and Pythagorean triples. mpmath is only needed for this test (`pip install mpmath`). - The fast path's error bounds are tested directly, not only through its answers. A bound that is too small would rarely change an answer, but it would make one wrong eventually. - `test/fb_check.py` runs random operations on random full-width balls, with and without errors. Using exact fractions, it checks that every corner of the operands gives a true result inside the result ball. The largest error / bound seen is 1.000 for multiplication and addition, 0.68 for division and 0.37 for square root. - `test/fast_check.py` evaluates every function's fast ball on the test inputs. It checks with mpmath that the true value lies inside; the largest error / bound seen is 0.64. - `test/fast_mutants.sh` plants 9 bugs in the fast path, and these checks catch all 9. The bugs include a dropped error term, a product wrongly taken as exact, an off table entry, a dropped truncation bound, and a missing part of π/2. The unmutated code passes. - `test/run.sh` runs everything. ## Speed It is software floating point, so expect it to be about 100 times slower than the hardware. On a 32-thread CPU, summing op(i/7, (i+1)/3) over 2^20 values of i in parallel took 0.32 s for add, 0.33 s for mul, 0.47 s for div, 0.49 s for sqrt and 0.51 s for fma. That includes making the inputs, which takes 0.17 s on its own. NumPy does one of these operations over 2^20 elements in about 1.5 ms on one thread (`test/bench.bend`). Text, on the same machine: - `show`: 2^20 values in 2.45 s on 32 threads, about 10 times slower than Python's `repr`. - `parse`, one thread: about 2.7 µs for a short number like `%.6g` gives; about 15 µs for a 17-digit `repr`; about 45 µs for exponents out to ±300. Python's `float()` takes about 0.1 µs. ## Not yet Fixed-digit formatting (`%.Nf`, `%.Ne`), 64-bit integer conversions, the other rounding modes, and a fast path for very large trigonometric arguments (from 2^30 they take the exact, slower reduction).