# softfpu
softfpu implements 32-, 64- and 80-bit floating-point arithmetic in safe Rust.
Addition, subtraction, multiplication, division and square root are correctly
rounded and report exception flags. The library uses only `core` and requires no
allocation or global state.
**Intel x87 transcendentals.** softfpu computes the results of all eight x87
transcendental instructions. Its result bits and status flags matched Intel
hardware on every operand tested, even when Intel's `fsin` differed from the
correctly rounded sine in the last bit.
[Hardware evidence](doc/transcendentals.md#delivery-and-evidence)
**Arithmetic throughput.** In benchmarks of 64- and 80-bit addition,
multiplication, division and square root, softfpu matched or beat Berkeley
SoftFloat 3e in every native comparison and was faster in every wasm32
comparison under V8. For 80-bit multiplication, softfpu delivered 1.57–2.98×
Berkeley's throughput natively and 1.11–2.37× in wasm32.
[Benchmarks](doc/performance.md)
## Basic arithmetic
Add the crate with `cargo add softfpu`. The
[API documentation](https://docs.rs/softfpu) covers operand requirements, result
flags and examples.
```rust
use softfpu::{Double, Flags, math};
let one = Double::from_i32(1);
let ten = Double::from_i32(10);
let quotient = math::divide(one, ten);
assert_eq!(quotient.value, Double(0.1_f64.to_bits()));
assert_eq!(quotient.flags, Flags::INEXACT);
```
`math` works with both `Single` and `Double` and rounds to nearest, ties to
even. The lower-level API lets you choose the rounding mode, tininess rule, and
NaN policy.
## 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.** A core operation returns either a
finished value with flags or an intermediate the caller can round. The caller
can round the same intermediate for masked and unmasked x87 exceptions.
- **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.** Core arithmetic methods take a `nan::NanPolicy` type
parameter. The policy supplies the default NaN, quiets signalling NaNs and
selects the result when one or both operands are NaNs.
- **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.
- 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.
- The x87 constants of `fld1`, `fldl2t`, `fldl2e`, `fldpi`, `fldlg2`, `fldln2`
and `fldz`, rounded under the rounding control.
- x87 transcendentals: `sin` (`fsin`), `cos` (`fcos`), `sin_cos` (`fsincos`),
`tan` (`fptan`), `atan2` (`fpatan`), `exp2m1` (`f2xm1`), `y_log2` (`fyl2x`)
and `y_log2p1` (`fyl2xp1`).
- The SSE `rcpss` and `rsqrtss` approximations.
## Usage
### 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, Extended, Flags, 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 underflow.
let masked = x86::extended::round(u, Rounding::Nearest, Precision::Extended);
assert!(masked.tiny);
assert_eq!(masked.value.exponent(), 0);
// With underflow 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.flags.contains(Flags::UNDERFLOW));
assert_eq!(unmasked.value.exponent(), 24_576);
```
### x87 transcendentals
```rust
use softfpu::x86::{self, Extended, Flags, Rounding};
let one = Extended::from_i64(1);
let computed = x86::transcendental::cos(one).expect("1 is in range for fcos");
let cos = computed.settle(|u| x86::transcendental::round(u, Rounding::Nearest));
assert!(cos.flags.contains(Flags::INEXACT));
```
## The x87 transcendentals
The x87 algorithms 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. [Hardware evidence](doc/transcendentals.md#delivery-and-evidence)
The reconstruction reproduces Intel's quirks along with its values. For example,
Intel's `f2xm1(+1)` returns exactly 1 and still raises the precision exception
(`PE`), and so does softfpu's.
## 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.
- [Performance](doc/performance.md) compares throughput with Berkeley SoftFloat
3e, natively and in wasm32.
## 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 schedules were first reconstructed in C. That version 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 evidence](doc/transcendentals.md#delivery-and-evidence)
## License
softfpu is released under the MIT license. See [LICENSE](LICENSE).