softfpu 0.2.1

32-, 64- and 80-bit floating-point arithmetic in safe Rust, including Intel x87 transcendental functions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Integer arithmetic for the x87 kernels (doc/transcendentals.md#intermediate-precision).

use core::cmp::Ordering;
use core::ops::{Add, Div, Mul, Neg, Sub};

use crate::Extended;

// Number of low significand bits of a Jammed that a set sticky bit leaves
// undetermined. A quotient has 120 or 121 determined bits.
const UNDETERMINED: u32 = 8;

// An exact value, (-1)^negative × significand × 2^(exponent − 127). The
// significand has its leading one at bit 127. Zero has a zero significand, a
// zero exponent and a positive sign.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Dyadic {
    pub negative: bool,
    pub exponent: i32,
    pub significand: u128,
}

// Leading bits of a result and whether nonzero bits follow. A quotient can
// leave up to UNDETERMINED low significand bits unresolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Jammed {
    pub leading: Dyadic,
    pub sticky: bool,
}

impl Dyadic {
    pub(super) const ZERO: Dyadic = Dyadic {
        negative: false,
        exponent: 0,
        significand: 0,
    };
    pub(super) const ONE: Dyadic = Dyadic::new(false, 1, 0);

    // Returns (-1)^negative × integer × 2^exponent.
    pub(super) const fn new(negative: bool, integer: u128, exponent: i32) -> Dyadic {
        if integer == 0 {
            return Dyadic::ZERO;
        }
        let shift = integer.leading_zeros();
        Dyadic {
            negative,
            exponent: exponent + 127 - shift as i32,
            significand: integer << shift,
        }
    }

    // Decodes a finite operand. An exponent field of zero uses the smallest
    // normal scale before the significand is normalized.
    pub(super) fn from_extended(x: Extended) -> Dyadic {
        Dyadic::new(
            x.negative(),
            u128::from(x.significand),
            x.exponent().max(1) - Extended::BIAS - 63,
        )
    }

    pub(super) fn is_zero(self) -> bool {
        self.significand == 0
    }

    pub(super) fn magnitude(self) -> Dyadic {
        self.signed(false)
    }

    // Returns the value with the given sign. Zero stays positive.
    pub(super) fn signed(self, negative: bool) -> Dyadic {
        Dyadic {
            negative: negative && !self.is_zero(),
            ..self
        }
    }

    // Returns the value times 2^power.
    pub(super) fn scaled(self, power: i32) -> Dyadic {
        if self.is_zero() {
            return self;
        }
        Dyadic {
            exponent: self.exponent + power,
            ..self
        }
    }

    // Returns floor(|self| × 2^power). The result must fit in 64 bits.
    pub(super) fn floor(self, power: i32) -> u64 {
        let leading = self.exponent + power;
        if self.is_zero() || leading < 0 {
            return 0;
        }
        assert!(leading < 64);
        (self.significand >> (127 - leading)) as u64
    }

    // Checks whether |self| > |other|. Neither is zero.
    pub(super) fn exceeds(self, other: Dyadic) -> bool {
        (self.exponent, self.significand) > (other.exponent, other.significand)
    }
}

impl Jammed {
    pub(super) fn is_zero(self) -> bool {
        self.leading.is_zero()
    }

    // Returns the exact value. Panics if the sticky bit is set.
    pub(super) fn exact(self) -> Dyadic {
        assert!(!self.sticky);
        self.leading
    }

    // Returns the value with the given sign. Zero stays positive.
    pub(super) fn signed(self, negative: bool) -> Jammed {
        Jammed {
            leading: self.leading.signed(negative),
            ..self
        }
    }

    // Truncates the magnitude to `bits` significant bits.
    pub(super) fn truncated(self, bits: u32) -> Dyadic {
        assert!(bits <= 127 - UNDETERMINED);
        Dyadic {
            significand: self.leading.significand >> (128 - bits) << (128 - bits),
            ..self.leading
        }
    }

    // Rounds to `bits` significant bits, to nearest, ties to even.
    pub(super) fn nearest(self, bits: u32) -> Dyadic {
        assert!(bits <= 127 - UNDETERMINED);
        let unit = 1u128 << (128 - bits);
        let kept = self.leading.significand & !(unit - 1);
        let rest = self.leading.significand & (unit - 1);
        let up = match rest.cmp(&(unit >> 1)) {
            Ordering::Less => false,
            Ordering::Greater => true,
            Ordering::Equal => self.sticky || kept & unit != 0,
        };
        // A carry out of the significand leaves the next power of two.
        let (exponent, significand) = match kept.checked_add(if up { unit } else { 0 }) {
            Some(significand) => (self.leading.exponent, significand),
            None => (self.leading.exponent + 1, 1 << 127),
        };
        Dyadic {
            exponent,
            significand,
            ..self.leading
        }
    }
}

// Returns a kernel constant with a 67-bit significand whose leading bit
// weighs 2^exponent.
pub(super) const fn constant(negative: bool, significand: u128, exponent: i32) -> Dyadic {
    Dyadic::new(negative, significand, exponent - 66)
}

// Truncates the magnitude to 67 significant bits.
pub(super) fn truncate67(value: impl Into<Jammed>) -> Dyadic {
    value.into().truncated(67)
}

// Truncates the magnitude to 64 significant bits.
pub(super) fn truncate64(value: impl Into<Jammed>) -> Dyadic {
    value.into().truncated(64)
}

// Rounds to 64 significant bits, to nearest with ties to even.
pub(super) fn nearest64(value: impl Into<Jammed>) -> Dyadic {
    value.into().nearest(64)
}

impl From<Dyadic> for Jammed {
    fn from(leading: Dyadic) -> Jammed {
        Jammed {
            leading,
            sticky: false,
        }
    }
}

impl Neg for Dyadic {
    type Output = Dyadic;

    fn neg(self) -> Dyadic {
        self.signed(!self.negative)
    }
}

impl Neg for Jammed {
    type Output = Jammed;

    fn neg(self) -> Jammed {
        self.signed(!self.leading.negative)
    }
}

impl Mul for Dyadic {
    type Output = Jammed;

    fn mul(self, other: Dyadic) -> Jammed {
        if self.is_zero() || other.is_zero() {
            return Dyadic::ZERO.into();
        }
        let (high, low) = widening_mul(self.significand, other.significand);
        let exponent = self.exponent + other.exponent;
        let (exponent, significand, rest) = if high >> 127 == 1 {
            (exponent + 1, high, low)
        } else {
            (exponent, high << 1 | low >> 127, low << 1)
        };
        Jammed {
            leading: Dyadic {
                negative: self.negative != other.negative,
                exponent,
                significand,
            },
            sticky: rest != 0,
        }
    }
}

// Returns the 256-bit product of `a` and `b` as its high and low halves.
fn widening_mul(a: u128, b: u128) -> (u128, u128) {
    const WORD: u128 = (1 << 64) - 1;
    let (a1, a0) = (a >> 64, a & WORD);
    let (b1, b0) = (b >> 64, b & WORD);
    let high = a1 * b1;
    if a0 == 0 && b0 == 0 {
        return (high, 0);
    }
    let (low, cross_a, cross_b) = (a0 * b0, a0 * b1, a1 * b0);
    let middle = (low >> 64) + (cross_a & WORD) + (cross_b & WORD);
    (
        high + (cross_a >> 64) + (cross_b >> 64) + (middle >> 64),
        middle << 64 | low & WORD,
    )
}

impl Div for Dyadic {
    type Output = Jammed;

    // The divisor has at most 68 significant bits and is not zero.
    fn div(self, other: Dyadic) -> Jammed {
        assert!(!other.is_zero() && other.significand << 68 == 0);
        if self.is_zero() {
            return Dyadic::ZERO.into();
        }
        // Each remainder fits in 68 bits before the 60-bit shift.
        let divisor = other.significand >> 60;
        let (first, remainder) = (self.significand / divisor, self.significand % divisor);
        let remainder = remainder << 60;
        let (second, remainder) = (remainder / divisor, remainder % divisor);
        let quotient = (first << 60) + second;
        let shift = quotient.leading_zeros();
        assert!(shift <= UNDETERMINED);
        Jammed {
            leading: Dyadic {
                negative: self.negative != other.negative,
                exponent: self.exponent - other.exponent + 7 - shift as i32,
                significand: quotient << shift,
            },
            sticky: remainder != 0,
        }
    }
}

impl Add<Jammed> for Dyadic {
    type Output = Jammed;

    // An inexact addend requires an exponent gap of at least UNDETERMINED.
    fn add(self, other: Jammed) -> Jammed {
        add(self.into(), other)
    }
}

impl Add for Dyadic {
    type Output = Jammed;

    fn add(self, other: Dyadic) -> Jammed {
        add(self.into(), other.into())
    }
}

impl Sub for Dyadic {
    type Output = Jammed;

    fn sub(self, other: Dyadic) -> Jammed {
        add(self.into(), (-other).into())
    }
}

// Aligns both operands to the larger magnitude, which must be exact in at
// most 127 bits. Close operands must align exactly for cancellation
// (doc/transcendentals.md#intermediate-precision).
fn add(a: Jammed, b: Jammed) -> Jammed {
    if a.is_zero() {
        return b;
    }
    if b.is_zero() {
        return a;
    }
    let (large, small) = if b.leading.exceeds(a.leading) {
        (b, a)
    } else {
        (a, b)
    };
    assert!(!large.sticky && large.leading.significand & 1 == 0);
    let (large, small_sticky, small) = (large.leading, small.sticky, small.leading);
    // The window holds the larger operand's leading bit at bit 126. Bit 127
    // stays free for a carry.
    let distance = (i64::from(large.exponent) - i64::from(small.exponent) + 1).min(128) as u32;
    let (shifted, discarded) = if distance == 128 {
        (0, true)
    } else {
        (
            small.significand >> distance,
            small.significand << (128 - distance) != 0,
        )
    };
    let sticky = discarded || small_sticky;
    assert!(!small_sticky || distance > UNDETERMINED);
    assert!(!sticky || distance > 2);
    let window = large.significand >> 1;
    let sum = if large.negative == small.negative {
        window + shifted
    } else {
        // Subtract the extra unit when the discarded fraction is nonzero.
        window - shifted - u128::from(sticky)
    };
    Jammed {
        // Bit 126 of the window weighs 2^large.exponent.
        leading: Dyadic::new(large.negative, sum, large.exponent - 126),
        sticky,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Returns integer × 2^exponent.
    fn d(integer: u128, exponent: i32) -> Dyadic {
        Dyadic::new(false, integer, exponent)
    }

    #[test]
    fn a_product_keeps_128_bits_and_reports_the_rest() {
        // (2^66 + 1)² = 2^132 + 2^67 + 1 has 133 bits.
        let a = d((1 << 66) + 1, 0);
        let product = a * a;
        assert_eq!(product.leading, d((1 << 127) + (1 << 62), 5));
        assert!(product.sticky);
        assert_eq!(d(3, 0) * d(5, -4), d(15, -4).into());
    }

    #[test]
    fn a_quotient_reports_its_remainder() {
        let third = d(1, 0) / d(3, 0);
        assert!(third.sticky);
        assert_eq!(truncate67(third), d((1 << 68) / 3, -68));
        assert_eq!(d(6, 0) / d(3, 0), d(2, 0).into());
    }

    #[test]
    fn a_midpoint_rounds_to_even_unless_bits_follow() {
        // 65-bit values whose last bit is half a unit of the 64-bit result.
        let even = d((1 << 64) + 1, 0);
        let odd = d((1 << 64) + 3, 0);
        assert_eq!(nearest64(even), d(1 << 63, 1));
        assert_eq!(nearest64(odd), d((1 << 63) + 2, 1));
        let above = Jammed {
            leading: even,
            sticky: true,
        };
        assert_eq!(nearest64(above), d((1 << 63) + 1, 1));
        // The carry out of the significand gives the next power of two.
        assert_eq!(nearest64(d((1 << 65) - 1, 0)), d(1, 65));
    }

    #[test]
    fn a_difference_borrows_for_the_bits_it_discards() {
        let difference = d(1, 0) - d(1, -200);
        assert!(difference.sticky);
        assert_eq!(truncate67(difference), d((1 << 67) - 1, -67));
    }

    #[test]
    fn a_sum_reports_the_bits_it_discards() {
        // 1 + 2^-64 is midway between two 64-bit values. The small addend
        // puts the sum above the midpoint.
        let sum = d((1 << 64) + 1, -64) + d(1, -200);
        assert!(sum.sticky);
        assert_eq!(nearest64(sum), d((1 << 63) + 1, -63));
    }

    #[test]
    fn a_close_difference_is_exact() {
        let difference = d((1 << 66) + 1, -66) - d(1, 0);
        assert_eq!(difference, d(1, -66).into());
    }
}