# 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. 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.1.0/float64.bend as F import bend-float64@0.1.1.0/text.bend as T 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' ``` ## 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)` | | 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. ## 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. - `mutants.sh` plants 39 single bugs, and the laws catch all 39. - 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. - `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/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`), `exp`/`log`/`sin`/`cos`/`pow`, 64-bit integer conversions, and the other rounding modes.