# softfpu
softfpu implements correctly rounded 32-, 64- and 80-bit floating-point
arithmetic in software, in safe Rust. The library operates on raw bit patterns.
It keeps no global state, does not allocate, and needs neither the standard
library nor any dependency.
An arithmetic operation returns either a finished value and its flags or an
intermediate for the caller to round. The caller can round the same intermediate
for different range responses without repeating the arithmetic. The `x86` layer
adds x86 NaN propagation, x87 precision control, the unmasked x87 and SSE
responses, the SSE reciprocal tables, and x87 transcendental kernels that
reproduce Intel hardware's results on every operand tested.
## Features
- **Bit-pattern formats.** `Single`, `Double` and `Extended` store raw
encodings, not host `f32` or `f64` values. They preserve NaN payloads, signed
zeros and noncanonical 80-bit encodings: unnormals, pseudo-NaNs,
pseudo-infinities, pseudo-denormals and MMX-aliased bit patterns.
- **Computation separated from rounding.** An arithmetic operation returns a
`Computed` result. `Finished` holds a value and its flags. `Unfinished` holds
an `Unrounded` intermediate with a sign, an unbiased exponent, a normalized
significand and a fractional tail. The caller rounds that intermediate once
for the response it needs: masked gradual underflow, the unmasked x87 exponent
adjustment of 24,576, or unmasked SSE exception reporting. The instruction
caller applies SSE flush to zero.
- **Complete rounding metadata.** A `Rounded` result reports its value and its
exception flags. It also reports whether rounding increased the magnitude,
which the x87 status word needs for `C1`, and whether the result was tiny
under the selected `Tininess` rule.
- **NaN policies chosen at compile time.** The core formats take a
`nan::NanPolicy` type parameter for the default NaN, quieting and operand
selection. No architecture is fixed when the crate is built.
- **The `x86` layer.**
- x86 NaN selection. SSE operations on 32 and 64 bits prefer the first
operand. x87 operations on 80 bits choose by signalling state, significand
and sign.
- The six architectural `Exceptions` (`IE`, `DE`, `ZE`, `OE`, `UE`, `PE`) and
integer-indefinite results for failed conversions.
- x87 precision control at 24, 53 and 64 bits over the 15-bit extended
exponent.
- The values of `fscale`, `fxtract`, `fprem`, `fprem1` and the packed BCD
instructions, including the progress of a partial remainder.
- x87 transcendentals (`sin`, `cos`, `sin_cos`, `tan`, `atan2`, `exp2m1`,
`y_log2`, `y_log2p1`) and the SSE `rcpss` and `rsqrtss` approximations.
- **No unsafe code.** The library uses only `core`.
## Usage
### Basic arithmetic
```rust
use softfpu::x86::{Double, Exceptions, Real, Rounding};
let a = Double(1.0_f64.to_bits());
let b = Double(10.0_f64.to_bits());
let quotient = <Double as Real>::divide(a, b)
.settle(|u| <Double as Real>::round(u, Rounding::Nearest));
assert_eq!(quotient.value, Double(0.1_f64.to_bits()));
assert!(quotient.exceptions.contains(Exceptions::PE));
```
### Masked and unmasked x87 rounding
`Unrounded` is `Copy`. A caller can inspect the masked result and, when an
overflow or underflow exception is unmasked, round the same intermediate again
with the x87 exponent adjustment.
```rust
use softfpu::Computed;
use softfpu::x86::{self, Exceptions, Extended, Precision, Rounding};
let min_normal = Extended { sign_exponent: 0x0001, significand: 1 << 63 };
let half = Extended { sign_exponent: 0x3FFE, significand: 1 << 63 };
let Computed::Unfinished(u) = x86::extended::multiply(min_normal, half) else {
unreachable!();
};
// Half the smallest normal number is an exact denormal. Masked rounding
// raises no UE.
let masked = x86::extended::round(u, Rounding::Nearest, Precision::Extended);
assert!(masked.tiny);
assert_eq!(masked.value.exponent(), 0);
// With UE unmasked, the result is normal and its exponent is adjusted by
// 24,576.
let unmasked = x86::extended::round_unmasked(u, Rounding::Nearest, Precision::Extended);
assert!(unmasked.exceptions.contains(Exceptions::UE));
assert_eq!(unmasked.value.exponent(), 24_576);
```
### x87 transcendentals
```rust
use softfpu::x86::{self, Exceptions, Extended, Rounding};
let one = Extended::from_i64(1);
if let Some(computed) = x86::transcendental::cos(one) {
let cos = computed.settle(|u| x86::transcendental::round(u, Rounding::Nearest));
assert!(cos.exceptions.contains(Exceptions::PE));
let _c1: bool = cos.rounded_up;
}
```
### The architecture-neutral core
Use the methods on `softfpu::{Single, Double, Extended}` with your own
implementation of `softfpu::nan::NanPolicy`. Pass the `Tininess` rule you want
when you round an intermediate.
Run `cargo doc --lib --open` for the API, including operand requirements, result
flags and examples.
## The x87 transcendentals
The Intel SDM bounds the error of `fsin`, `fcos`, `fsincos`, `fptan`, `fpatan`,
`f2xm1`, `fyl2x` and `fyl2xp1` at 1 to 1.5 units in the last place. The
processor's algorithm determines the exact result bits, `C1`, and whether an
exact result raises `PE`. Intel hardware behaves as follows:
- The trigonometric kernels reduce the argument by multiples of π/2 with a
constant of 66 fractional bits. `fsin` and `fcos` use a different evaluation
order from `fsincos`.
- The final rounding raises `PE` even for exact results such as `f2xm1(+1) = 1`
and `fyl2x(1024, 1) = 10`.
- Near the boundary for tiny `fcos` arguments, two inputs can both produce +1
with different values of `C1`.
`x86::transcendental` reproduces the hardware's schedules over 128-bit dyadic
significands with a sticky bit. Most constants have 67-bit significands, and the
multiples of π have up to 70. Each intermediate step is exact or rounded to 64
or 67 bits, and the closing operation is rounded once. A final sum or product
supplies up to 128 leading bits, and a quotient supplies 120 or 121.
An evaluation in 113-bit arithmetic rounds twice. Rounding first to 113 bits can
move the result onto a midpoint between two 64-bit values. Rounding that
midpoint to 64 bits can then change the last bit and `C1` across a band of
adjacent inputs. A band holds up to 8,192 inputs for `fcos` near 2^-32 and up to
10,486 for `fpatan`.
The schedules were reconstructed from the Intel SDM, Intel's 2015 paper on
trigonometric range reduction, Ken Shirriff's
[reading of the Pentium's constant ROM](https://www.righto.com/2025/01/pentium-floating-point-ROM.html)
from die photographs, and measurements on hardware. Targeted comparisons
distinguished many intermediate rounding steps, and several steps remain
assumptions.
[Kernel schedules and their limits](doc/transcendentals.md#delivery-and-evidence)
## Implementation
- [Design](doc/design.md) covers intermediate precision, cold returns, inlining
attributes and NaN policies.
- [Rounding](doc/rounding.md) derives the rounding decision, tininess and range
responses.
- [Addition and subtraction](doc/addition.md) covers alignment, cancellation and
sticky bits.
- [Multiplication](doc/multiplication.md) derives the product widths for each
format.
- [Division](doc/division.md) derives the quotient and remainder bounds for all
three kernels, and covers the x87 partial remainder.
- [Square root](doc/square-root.md) covers the seed table, refinement and final
residual.
- [Comparison and conversions](doc/conversions.md) covers numeric ordering,
format changes and rounding at the units position.
- [x87 transcendental functions](doc/transcendentals.md) covers the internal
precision, range reduction, polynomial schedules and hardware evidence.
- [SSE reciprocal approximations](doc/reciprocals.md) covers table lookup,
special operands and the relative-error bound.
## Verification
| `cargo test --doc` | Public API examples |
| `cargo test` | Crate tests, the integer rounding model, external NaN-policy tests, and a replay of 45,610 x87 transcendental results recorded on Intel hardware |
| `cargo test --release --test testfloat -- --ignored` | Generated cases against Berkeley TestFloat, with the reference library following x86's NaN rules. Requires `testfloat_gen` on `PATH`. |
[tests/README.md](tests/README.md) explains how to build `testfloat_gen` and
describes the recorded results.
TestFloat checks values and exception flags under the masked response. The
crate's model tests check `rounded_up`, `tiny` and the unmasked responses
against exact integer arithmetic.
The C reconstruction of the transcendentals matched one Intel processor across
13.93 billion executions, with exceptions masked and with random exception
masks. A second Intel processor, of a different core design, reproduced the
recorded observations. The Rust kernels matched the reconstruction on worked
examples, recorded observations and four million seeded cases per instruction.
`cargo test` replays the 45,610 recorded observations that have every exception
masked and valid operands.
[Hardware comparisons](doc/transcendentals.md#delivery-and-evidence)
## License
softfpu is released under the MIT license. See [LICENSE](LICENSE).