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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
//! x87 transcendental functions on supported extended encodings. The caller
//! handles unsupported operands and denormal-operand exceptions. NaNs propagate
//! under the [`super::X86`] policy. Invalid operations return the default NaN with IE.
//!
//! Settle an unfinished kernel result with this module's [`round`] or
//! [`round_unmasked`]. Both use full extended precision and raise PE for every unfinished result.
//! The four trigonometric functions return `None` for finite arguments outside
//! the hardware reduction range.
//!
//! ```
//! use softfpu::x86::{Exceptions, Extended, Rounding, transcendental};
//!
//! let cosine = |x| transcendental::cos(x).unwrap()
//!     .settle(|v| transcendental::round(v, Rounding::Nearest));
//! let zero = cosine(Extended::from_i64(0));
//! let tiny = cosine(Extended { sign_exponent: 0x3fba, significand: 1 << 63 }); // 2^-69
//! assert_eq!(zero.value, Extended::from_i64(1));
//! assert_eq!(tiny.value, zero.value);
//! assert_eq!(zero.exceptions, Exceptions::NONE);
//! assert_eq!(tiny.exceptions, Exceptions::PE);
//! ```

mod arctangent;
mod dyadic;
mod exponential;
mod logarithm;
mod polynomial;
mod trigonometric;

use dyadic::{Dyadic, Jammed};

use super::extended;
use super::{Computed, Exceptions, Extended, Precision, Rounded, Rounding};
use crate::Unrounded;

type Result = Computed<Extended>;

const ONE: Extended = Extended {
    sign_exponent: Extended::BIAS as u16,
    significand: 1 << 63,
};

/// Rounds an unrounded kernel result with the masked response. Every such
/// result raises PE. A result delivered with a zero exponent field also raises
/// UE, even when it is exact.
#[inline]
pub fn round(value: Unrounded<Extended>, rounding: Rounding) -> Rounded<Extended> {
    let mut rounded = extended::round(value, rounding, Precision::Extended);
    rounded.exceptions |= Exceptions::PE;
    if rounded.value.sign_exponent & 0x7FFF == 0 {
        rounded.exceptions |= Exceptions::UE;
    }
    rounded
}

/// Rounds an unrounded kernel result with the unmasked response to OE or UE.
/// Every such result raises PE.
#[inline]
pub fn round_unmasked(value: Unrounded<Extended>, rounding: Rounding) -> Rounded<Extended> {
    let mut rounded = extended::round_unmasked(value, rounding, Precision::Extended);
    rounded.exceptions |= Exceptions::PE;
    rounded
}

/// Approximates sin(x). Preserves signed zero. Infinity is invalid.
/// Returns `None` for finite `|x| ≥ 2^63`.
#[inline]
pub fn sin(x: Extended) -> Option<Result> {
    Some(match Angle::of(x)? {
        Angle::Invalid(nan) => nan,
        Angle::Zero => exact(x),
        Angle::Tiny(v) => deliver(v.into()),
        Angle::Reducible(v) => deliver(trigonometric::component(v, false)),
    })
}

/// Approximates cos(x). Either signed zero gives one. Infinity is invalid.
/// Returns `None` for finite `|x| ≥ 2^63`.
#[inline]
pub fn cos(x: Extended) -> Option<Result> {
    Some(match Angle::of(x)? {
        Angle::Invalid(nan) => nan,
        Angle::Zero => exact(ONE),
        Angle::Tiny(_) => deliver(Dyadic::ONE.into()),
        Angle::Reducible(v) => deliver(trigonometric::component(v, true)),
    })
}

/// Approximates sine and cosine in that order for the paired instruction.
/// Signed zero gives (x, 1). Infinity is invalid for both results.
/// Returns `None` for finite `|x| ≥ 2^63`.
#[inline]
pub fn sin_cos(x: Extended) -> Option<(Result, Result)> {
    Some(match Angle::of(x)? {
        Angle::Invalid(nan) => (nan, nan),
        Angle::Zero => (exact(x), exact(ONE)),
        Angle::Tiny(v) => (deliver(v.into()), deliver(Dyadic::ONE.into())),
        Angle::Reducible(v) => {
            let (sine, cosine) = trigonometric::pair(v);
            (deliver(sine), deliver(cosine))
        }
    })
}

/// Approximates tan(x). Preserves signed zero. Infinity is invalid.
/// Returns `None` for finite `|x| ≥ 2^63`.
#[inline]
pub fn tan(x: Extended) -> Option<Result> {
    Some(match Angle::of(x)? {
        Angle::Invalid(nan) => nan,
        Angle::Zero => exact(x),
        Angle::Tiny(v) => deliver(v.into()),
        Angle::Reducible(v) => deliver(trigonometric::tangent(v)),
    })
}

/// Approximates `2^x − 1`. Preserves signed zero. At ±1 the result is exact and raises PE. Negative infinity gives −1 and
/// positive infinity gives itself. For finite `|x| > 1`, returns `x` with PE.
#[inline]
pub fn exp2m1(x: Extended) -> Result {
    if x.is_nan() {
        return nan(x, x);
    }
    if x.is_zero() {
        return exact(x);
    }
    if x.is_infinity() {
        return exact(if x.negative() { negated(ONE) } else { x });
    }
    let exponent = x.exponent();
    let one = exponent == Extended::BIAS && x.significand == 1 << 63;
    if exponent >= Extended::BIAS && !one {
        return Computed::Finished(x, Exceptions::PE);
    }
    let v = Dyadic::from_extended(x);
    deliver(if one {
        // 2^1 − 1 = 1 and 2^-1 − 1 = −1/2.
        Dyadic::new(x.negative(), 1, -i32::from(x.negative())).into()
    } else if exponent < Extended::BIAS - 68 {
        exponential::tiny(v)
    } else {
        exponential::evaluate(v)
    })
}

/// Approximates `y × log2(x)`. Negative nonzero `x` is invalid. So are zero `y`
/// at zero or infinite `x`, and infinite `y` at `x = 1`. For zero `x` and
/// nonzero `y`, returns infinity with sign opposite to `y`. Raises ZE in
/// this case only if `y` is finite.
#[inline]
pub fn y_log2(x: Extended, y: Extended) -> Result {
    if x.is_nan() || y.is_nan() {
        return nan(x, y);
    }
    if x.negative() && !x.is_zero() {
        return invalid();
    }
    if x.is_zero() {
        return if y.is_zero() {
            invalid()
        } else {
            Computed::Finished(
                Extended::infinity(!y.negative()),
                Exceptions::ZE.when(!y.is_infinity()),
            )
        };
    }
    if x.is_infinity() {
        return if y.is_zero() {
            invalid()
        } else {
            exact(Extended::infinity(y.negative()))
        };
    }
    if x == ONE {
        return if y.is_infinity() {
            invalid()
        } else {
            exact(Extended::zero(y.negative()))
        };
    }
    // log2(x) is negative for x < 1.
    let negative = y.negative() != (x.exponent() < Extended::BIAS);
    if y.is_zero() {
        return exact(Extended::zero(negative));
    }
    if y.is_infinity() {
        return exact(Extended::infinity(negative));
    }
    deliver(Dyadic::from_extended(y) * logarithm::log2(Dyadic::from_extended(x)))
}

/// Approximates `y × log2(1 + x)`. After NaN propagation, negative infinity for `x`
/// and a zero operand paired with infinity are invalid. For finite `x ≤ −1`
/// and finite nonzero `y`, returns `x` with PE. If both operands are finite
/// and either is zero, returns zero with the sign of `x × y`.
#[inline]
pub fn y_log2p1(x: Extended, y: Extended) -> Result {
    if x.is_nan() || y.is_nan() {
        return nan(x, y);
    }
    if x.is_infinity() {
        return if x.negative() || y.is_zero() {
            invalid()
        } else {
            exact(Extended::infinity(y.negative()))
        };
    }
    let negative = x.negative() != y.negative();
    if y.is_infinity() {
        return if x.is_zero() {
            invalid()
        } else {
            exact(Extended::infinity(negative))
        };
    }
    if x.is_zero() || y.is_zero() {
        return exact(Extended::zero(negative));
    }
    if x.negative() && x.exponent() >= Extended::BIAS {
        return Computed::Finished(x, Exceptions::PE);
    }
    deliver(Dyadic::from_extended(y) * logarithm::log2p1(Dyadic::from_extended(x)))
}

/// Approximates the angle of `(x, y)` in radians, with the sign of `y`. Signed zeros
/// and infinities select the corresponding axis or quadrant angle.
#[inline]
pub fn atan2(y: Extended, x: Extended) -> Result {
    if x.is_nan() || y.is_nan() {
        return nan(x, y);
    }
    let constant = |angle: Dyadic| deliver(angle.signed(y.negative()).into());
    if x.is_infinity() && y.is_infinity() {
        return constant(if x.negative() {
            arctangent::THREE_QUARTERS_PI
        } else {
            arctangent::QUARTER_PI
        });
    }
    if y.is_infinity() {
        return constant(arctangent::HALF_PI);
    }
    if x.is_infinity() || y.is_zero() {
        return if x.negative() {
            constant(arctangent::PI)
        } else {
            exact(Extended::zero(y.negative()))
        };
    }
    if x.is_zero() {
        return constant(arctangent::HALF_PI);
    }
    let angle = arctangent::angle(Dyadic::from_extended(x), Dyadic::from_extended(y));
    // A finite nonzero pair gives a nonzero angle (doc/transcendentals.md#arctangent).
    assert!(!angle.is_zero());
    deliver(angle.signed(y.negative()))
}

// Operand classes of the four trigonometric forms.
enum Angle {
    // An infinity or a NaN, with its result.
    Invalid(Result),
    Zero,
    // A nonzero argument with |x| < 2^-68. Sine and tangent use x, cosine uses
    // one, and all four instruction forms raise PE.
    Tiny(Dyadic),
    Reducible(Dyadic),
}

impl Angle {
    // Classifies x. Returns None for a finite x with |x| ≥ 2^63.
    fn of(x: Extended) -> Option<Angle> {
        if x.is_nan() {
            return Some(Angle::Invalid(nan(x, x)));
        }
        if x.is_infinity() {
            return Some(Angle::Invalid(invalid()));
        }
        if x.is_zero() {
            return Some(Angle::Zero);
        }
        let exponent = x.exponent();
        if exponent >= Extended::BIAS + 63 {
            return None;
        }
        Some(if exponent < Extended::BIAS - 68 {
            Angle::Tiny(Dyadic::from_extended(x))
        } else {
            Angle::Reducible(Dyadic::from_extended(x))
        })
    }
}

fn exact(value: Extended) -> Result {
    Computed::Finished(value, Exceptions::NONE)
}

fn invalid() -> Result {
    Computed::Finished(extended::DEFAULT_NAN, Exceptions::IE)
}

// Selects the quiet NaN result. Either signalling operand raises IE.
fn nan(a: Extended, b: Extended) -> Result {
    let (value, exceptions) = extended::propagate_nan(a, b);
    Computed::Finished(value, exceptions)
}

fn negated(value: Extended) -> Extended {
    Extended {
        sign_exponent: value.sign_exponent ^ 0x8000,
        ..value
    }
}

// Pass the leading bits and sticky bit to the finalizer. Deliver zero with PE.
fn deliver(value: Jammed) -> Result {
    let Dyadic {
        negative,
        exponent,
        significand,
    } = value.leading;
    if significand == 0 {
        return Computed::Finished(Extended::zero(negative), Exceptions::PE);
    }
    Computed::Unfinished(Unrounded::from_parts(
        negative,
        exponent,
        (significand >> 64) as u64,
        significand as u64 | u64::from(value.sticky),
    ))
}

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

    const fn x(sign_exponent: u16, significand: u64) -> Extended {
        Extended {
            sign_exponent,
            significand,
        }
    }

    const PLUS_ONE: Extended = x(0x3FFF, 1 << 63);
    const MINUS_ONE: Extended = x(0xBFFF, 1 << 63);
    const PLUS_ZERO: Extended = x(0, 0);
    const MINUS_ZERO: Extended = x(0x8000, 0);
    const PLUS_INFINITY: Extended = x(0x7FFF, 1 << 63);
    const MINUS_INFINITY: Extended = x(0xFFFF, 1 << 63);
    const QUIET_NAN: Extended = x(0x7FFF, 0xC000_0000_0000_0001);
    // The real indefinite, with IE.
    const INVALID: Result = Computed::Finished(x(0xFFFF, 0xC000_0000_0000_0000), Exceptions::IE);

    // Rounds a kernel result to nearest with the masked response.
    fn masked(result: Result) -> Rounded<Extended> {
        result.settle(|unrounded| round(unrounded, Rounding::Nearest))
    }

    #[test]
    fn the_trigonometric_range_ends_below_two_to_the_63() {
        let largest = x(0x403D, u64::MAX);
        let first_outside = x(0x403E, 1 << 63);
        assert!(sin(largest).is_some() && sin(first_outside).is_none());
        assert!(cos(largest).is_some() && cos(first_outside).is_none());
        assert!(sin_cos(largest).is_some() && sin_cos(first_outside).is_none());
        assert!(tan(largest).is_some() && tan(first_outside).is_none());
    }

    #[test]
    fn a_tiny_angle_returns_itself_and_a_cosine_of_one_with_pe() {
        // 1.5 × 2^-69.
        let tiny = x(0xBFBA, 0xC000_0000_0000_0000);
        for result in [sin(tiny), tan(tiny)] {
            let rounded = masked(result.expect("an operand in range"));
            assert_eq!((rounded.value, rounded.exceptions), (tiny, Exceptions::PE));
        }
        let cosine = masked(cos(tiny).expect("an operand in range"));
        assert_eq!(
            (cosine.value, cosine.exceptions),
            (PLUS_ONE, Exceptions::PE)
        );
    }

    #[test]
    fn f2xm1_at_plus_and_minus_one_is_exact_with_pe() {
        let minus_half = x(0xBFFE, 1 << 63);
        let at_one = masked(exp2m1(PLUS_ONE));
        assert_eq!(
            (at_one.value, at_one.exceptions),
            (PLUS_ONE, Exceptions::PE)
        );
        assert!(!at_one.rounded_up);
        let at_minus_one = masked(exp2m1(MINUS_ONE));
        assert_eq!(
            (at_minus_one.value, at_minus_one.exceptions),
            (minus_half, Exceptions::PE)
        );
    }

    #[test]
    fn fyl2x_of_zero_divides_by_zero_unless_y_is_infinite() {
        assert_eq!(
            y_log2(PLUS_ZERO, PLUS_ONE),
            Computed::Finished(MINUS_INFINITY, Exceptions::ZE)
        );
        assert_eq!(
            y_log2(MINUS_ZERO, MINUS_INFINITY),
            Computed::Finished(PLUS_INFINITY, Exceptions::NONE)
        );
        assert_eq!(y_log2(PLUS_ZERO, PLUS_ZERO), INVALID);
    }

    #[test]
    fn a_nan_operand_takes_precedence_over_the_domain() {
        let quiet = Computed::Finished(QUIET_NAN, Exceptions::NONE);
        assert_eq!(y_log2(MINUS_ONE, QUIET_NAN), quiet);
        assert_eq!(y_log2p1(MINUS_INFINITY, QUIET_NAN), quiet);
        assert_eq!(atan2(QUIET_NAN, PLUS_ZERO), quiet);
        assert_eq!(exp2m1(QUIET_NAN), quiet);
        assert_eq!(sin(QUIET_NAN), Some(quiet));
    }

    #[test]
    fn an_exact_zero_result_keeps_its_sign() {
        let zero = |value| Computed::Finished(value, Exceptions::NONE);
        // log2(1) = 0, with the sign of y.
        assert_eq!(y_log2(PLUS_ONE, MINUS_ONE), zero(MINUS_ZERO));
        assert_eq!(y_log2(PLUS_ONE, PLUS_ONE), zero(PLUS_ZERO));
        // log2(1 + 0) = 0, with the sign of x·y.
        assert_eq!(y_log2p1(MINUS_ZERO, PLUS_ONE), zero(MINUS_ZERO));
        assert_eq!(y_log2p1(MINUS_ZERO, MINUS_ONE), zero(PLUS_ZERO));
        // The angle of (x > 0, y = ±0) is y.
        assert_eq!(atan2(MINUS_ZERO, PLUS_ONE), zero(MINUS_ZERO));
        assert_eq!(exp2m1(MINUS_ZERO), zero(MINUS_ZERO));
        assert_eq!(sin(MINUS_ZERO), Some(zero(MINUS_ZERO)));
    }

    #[test]
    fn a_denormal_operand_has_the_smallest_normal_exponent() {
        // The smallest denormal is 2^-16445.
        assert_eq!(
            Dyadic::from_extended(x(0, 1)),
            Dyadic::new(false, 1, -16_445)
        );
        // A pseudo-denormal with the integer bit set is 2^-16382.
        assert_eq!(
            Dyadic::from_extended(x(0x8000, 1 << 63)),
            Dyadic::new(true, 1, -16_382)
        );
        assert_eq!(
            Dyadic::from_extended(x(1, 1 << 63)),
            Dyadic::new(false, 1, -16_382)
        );
    }

    #[test]
    fn a_result_passes_on_128_bits_and_whether_more_follow() {
        // 2^64 + 1 has its last bit in the first place below the significand.
        let leading = Dyadic::new(true, (1 << 64) + 1, 0);
        let unrounded =
            |extra| Computed::Unfinished(Unrounded::from_parts(true, 64, 1 << 63, extra));
        let exact = Jammed {
            leading,
            sticky: false,
        };
        assert_eq!(deliver(exact), unrounded(1 << 63));
        let inexact = Jammed {
            leading,
            sticky: true,
        };
        assert_eq!(deliver(inexact), unrounded(1 << 63 | 1));
        assert_eq!(
            deliver(Dyadic::ZERO.into()),
            Computed::Finished(PLUS_ZERO, Exceptions::PE)
        );
    }
}