tinymind 0.3.7

Neural networks for embedded Rust: a no_std, allocation-free port of the tinymind (C++) library, bit-exact with it
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! Signed fixed-point Q-format arithmetic, ported from tinymind (C++) `cpp/qformat.hpp`.
//!
//! The C++ `QValue<FixedBits, FractionalBits, IsSigned, RoundingPolicy, SaturatePolicy>`
//! picks its storage type from `FixedBits + FractionalBits` at compile time
//! (`QTypeChooser`). Stable Rust cannot compute a type from const-generic
//! arithmetic (that needs the nightly `generic_const_exprs` feature), so here the
//! storage type is an explicit parameter: `QValue<i32, 16>` is Q16.16 and
//! `QValue<i16, 8>` is Q8.8. The methods and operators are generated for each
//! supported storage type by a macro, each with the wider type C++ uses for
//! products and quotients (`i64` for `i32`, `i32` for `i16`).
//!
//! Only tinymind (C++)'s default policies are ported: `TruncatePolicy` (multiplication
//! drops the low bits) and `WrapPolicy` (addition and subtraction wrap modulo the
//! storage width).
//!
//! The module also defines [`Scalar`], the value-type trait every network is
//! generic over, implemented for these formats and for `f32` and `f64` (and the
//! deprecated [`Fixed`], its name up to 0.1.5).

use core::fmt;
use core::ops::{Add, AddAssign, Div, Mul, Sub};

/// A signed fixed-point value stored in `S` (`i16` or `i32`) with `FRAC`
/// fractional bits.
///
/// The derived `PartialOrd`/`Ord` compare the raw integer, which is exactly what
/// the C++ comparison operators do (they compare `getValue()`).
///
/// `FRAC` must be at least 1 and less than the storage width; anything else is a
/// compile-time error wherever the format's arithmetic is used:
///
/// ```compile_fail
/// // 40 fractional bits do not fit in i32 storage.
/// let x = tinymind::QValue::<i32, 40>::default();
/// let _ = x.to_f64();
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct QValue<S, const FRAC: u32>(S);

/// Q16.16: 16 integer bits (including sign), 16 fractional bits, `i32` storage.
pub type Q16_16 = QValue<i32, 16>;

/// Q8.8: 8 integer bits (including sign), 8 fractional bits, `i16` storage.
pub type Q8_8 = QValue<i16, 8>;

/// Prints the raw LSBs, matching the C++ `operator<<` (not the real value).
impl<S: fmt::Display, const FRAC: u32> fmt::Display for QValue<S, FRAC> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

/// A network's value type: the arithmetic a network needs from the numbers it
/// computes with. This is the Rust counterpart of the implicit "ValueType
/// concept" that the C++ templates rely on: in C++ a missing operator is a
/// template instantiation error, here it is a trait-bound error at the call
/// site.
///
/// Implemented for the [`QValue`] formats and for `f32` and `f64`: the networks
/// run in fixed point or in floating point, as tinymind (C++)'s do when
/// instantiated with a Q format, `float` or `double`. Called `Fixed` up to
/// 0.1.5; that name remains as a deprecated alias ([`Fixed`]).
pub trait Scalar:
    Copy
    + Default
    + PartialOrd
    + Add<Output = Self>
    + AddAssign
    + Sub<Output = Self>
    + Mul<Output = Self>
    + Div<Output = Self>
{
    /// 0.0
    const ZERO: Self;
    /// 1.0
    const ONE: Self;
    /// `2^-n`
    fn pow2_neg(n: u32) -> Self;
    /// Divide by a whole number (C++ `operator/=(int)`).
    fn div_int(self, n: i32) -> Self;
    /// `self * rhs` rounded toward zero (C++ `multiplyRoundTowardZero`), used
    /// for SGD's momentum and acceleration terms so that a delta weight no
    /// gradient refreshes decays to exactly 0. The default is `self * rhs`,
    /// right for floating point; the Q formats round their product toward
    /// zero instead of flooring it.
    fn mul_round_toward_zero(self, rhs: Self) -> Self {
        self * rhs
    }
    /// `self * rhs` rounded to nearest, ties away from zero (C++
    /// `multiplyRoundNearest`), used for SGD's step `learning rate *
    /// gradient`, so that steps smaller than the format's resolution do not
    /// all drift one way. The default is `self * rhs`, right for floating
    /// point; the Q formats round their product to nearest instead of
    /// flooring it.
    fn mul_round_nearest(self, rhs: Self) -> Self {
        self * rhs
    }
}

/// The name of [`Scalar`] up to 0.1.5, kept so that bounds written `V: Fixed`
/// still compile. Every [`Scalar`] is a `Fixed`; implement [`Scalar`] instead.
/// `Fixed` has no items of its own, so paths that name them through it
/// (`<V as Fixed>::ONE`, `Fixed::div_int(..)`) must name [`Scalar`].
///
/// ```
/// # #![allow(deprecated)]
/// use tinymind::{Fixed, Q16_16};
///
/// // Code written against 0.1.5 keeps compiling (with a deprecation warning).
/// fn one<V: Fixed>() -> V {
///     V::ONE
/// }
/// assert_eq!(one::<Q16_16>(), Q16_16::ONE);
/// assert_eq!(one::<f64>(), 1.0);
/// ```
#[deprecated(
    since = "0.2.0",
    note = "renamed to `Scalar`, which covers f32 and f64 as well as the Q formats"
)]
pub trait Fixed: Scalar {}

#[allow(deprecated)]
impl<T: Scalar> Fixed for T {}

/// `f32` and `f64` as network value types. `pow2_neg` builds the power of two
/// exactly; `div_int` divides by the integer converted to the float type, as
/// the C++ `value /= n` does.
macro_rules! impl_fixed_float {
    ($t:ty) => {
        impl Scalar for $t {
            const ZERO: Self = 0.0;
            const ONE: Self = 1.0;

            fn pow2_neg(n: u32) -> Self {
                let mut x: $t = 1.0;
                for _ in 0..n.min(1100) {
                    x *= 0.5;
                }
                x
            }

            fn div_int(self, n: i32) -> Self {
                self / (n as $t)
            }
        }
    };
}

impl_fixed_float!(f32);
impl_fixed_float!(f64);

/// Square root of a non-negative value (C++ `SquareRootApproximation`):
/// integer Newton iteration on `raw << FRAC` in the wide type, which gives the
/// floor of the exact root in raw units. Zero and negative values give zero. The
/// Adam and RMSprop optimizers use it.
pub trait Sqrt {
    /// `floor(sqrt(self))` in this format; 0 for `self <= 0`.
    fn sqrt(self) -> Self;
}

/// Generates everything that depends on the storage type: `$s` is the storage,
/// `$wide` the C++ `MultiplicationResultFullWidthValueType` /
/// `DivisionResultFullWidthValueType` for it (twice the width).
macro_rules! impl_qvalue {
    ($s:ty, $wide:ty) => {
        impl<const FRAC: u32> QValue<$s, FRAC> {
            /// Compile-time format check, evaluated once per instantiated format.
            /// The C++ library does the same job with `static_assert`. Every method
            /// whose arithmetic depends on `FRAC` evaluates it, so an invalid format
            /// such as `QValue<i32, 40>` fails to compile wherever it is used, even
            /// when the value came from `Default`.
            const FORMAT_OK: () = assert!(
                FRAC >= 1 && FRAC < <$s>::BITS,
                "QValue needs at least 1 fractional bit and fewer than the storage width"
            );

            /// Number of fractional bits (`FRAC`).
            pub const FRACTIONAL_BITS: u32 = FRAC;
            /// Number of integer bits, including the sign bit (storage width - `FRAC`).
            pub const FIXED_BITS: u32 = <$s>::BITS - FRAC;
            /// 0.0
            pub const ZERO: Self = Self::from_raw(0);
            /// 1.0. When `FRAC` is one less than the storage width (Q1.15, Q1.31)
            /// there are no integer bits besides the sign, 1.0 is not
            /// representable, and this wraps to -1.0 (the storage type's minimum).
            pub const ONE: Self = Self::from_int(1);

            /// Build from raw LSBs (C++ `QValue(FullWidthFieldType)` / `setValue(raw)`).
            pub const fn from_raw(raw: $s) -> Self {
                let () = Self::FORMAT_OK;
                Self(raw)
            }

            /// Build from a whole number (C++ `QValue(fixedPart, 0)`). The fixed part
            /// is truncated to `FIXED_BITS`, as the C++ `fromParts` does, which is the
            /// same as shifting left and letting the high bits fall off: in Q8.8, 200
            /// becomes -56.
            pub const fn from_int(n: i32) -> Self {
                let () = Self::FORMAT_OK;
                Self(((n as u32) << FRAC) as $s)
            }

            /// `2^-n`, used for tinymind (C++)'s default learning/momentum/acceleration rates.
            ///
            /// For `n > FRAC`, `2^-n` is below the format's resolution and the result
            /// is [`ZERO`](Self::ZERO): the value truncated to the format, as
            /// TruncatePolicy rounds every other result. `pow2_neg(0)` is
            /// [`ONE`](Self::ONE), with the same caveat for formats without integer bits.
            pub const fn pow2_neg(n: u32) -> Self {
                if n > FRAC {
                    return Self::from_raw(0);
                }
                Self::from_raw((1 as $s) << (FRAC - n))
            }

            /// Raw LSBs (C++ `getValue()`).
            pub const fn raw(self) -> $s {
                self.0
            }

            /// Real-number view, computed as the C++ example does: `raw / 2^FRAC` in `f64`.
            pub fn to_f64(self) -> f64 {
                let () = Self::FORMAT_OK;
                f64::from(self.0) / f64::from(1u32 << FRAC)
            }

            /// Truncating conversion from `f64` (C++
            /// `setValue(static_cast<FullWidthValueType>(x * 2^FRAC))`). Out-of-range
            /// input saturates; in C++ it is undefined behaviour.
            pub fn from_f64_trunc(x: f64) -> Self {
                Self::from_raw((x * f64::from(1u32 << FRAC)) as $s)
            }

            /// `self * rhs` with the product rounded toward zero instead of
            /// floored (C++ `multiplyRoundTowardZero`): the same widening and
            /// wrap to the storage width as `*`. SGD uses it for the momentum
            /// and acceleration terms: floored, `0.5 * (-1 LSB)` stays -1 LSB,
            /// so a delta weight no gradient refreshes would never decay.
            pub fn mul_round_toward_zero(self, rhs: Self) -> Self {
                let () = Self::FORMAT_OK;
                let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
                // Toward zero without a branch: a negative product gets
                // 2^FRAC - 1 added before the flooring shift. |product| <=
                // 2^(2 * storage bits - 2), so the sum cannot overflow.
                let bias = (product >> (<$wide>::BITS - 1)) & ((1 << FRAC) - 1);
                Self(((product + bias) >> FRAC) as $s)
            }

            /// `self * rhs` with the product rounded to nearest, ties away
            /// from zero, instead of floored (C++ `multiplyRoundNearest`): the
            /// same widening and wrap to the storage width as `*`. SGD uses it
            /// for the step `learning rate * gradient`: floored, a step smaller
            /// than one LSB is 0 when positive but a whole -1 LSB when
            /// negative, so weights with small gradients drift down.
            pub fn mul_round_nearest(self, rhs: Self) -> Self {
                let () = Self::FORMAT_OK;
                let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
                // Half away from zero without a branch: adding half and then
                // flooring rounds half up, which is right for a positive
                // product; a negative one also gets the sign word, -1, added,
                // which turns its ties down (away from zero) and leaves every
                // other value where half up puts it. Kani proves it for every
                // input. |product| <= 2^(2 * storage bits - 2), so the sum
                // cannot overflow.
                let sign = product >> (<$wide>::BITS - 1);
                Self(((product + (1 << (FRAC - 1)) + sign) >> FRAC) as $s)
            }

            /// Divide by a whole number, truncating toward zero (C++
            /// `QValue::operator/=(int)`). This is *not* the same as dividing by
            /// `QValue::from_int(n)`.
            pub const fn div_int(self, n: i32) -> Self {
                if n == 0 {
                    return Self::div_by_zero(self.0);
                }
                // C++ applyInteger works in int64 for every format up to 32 bits.
                Self((self.0 as i64 / n as i64) as $s)
            }

            /// C++ `ZeroToleranceCalculator`: true when `|raw| < 1 << (FRAC - 7)` for
            /// formats with more than 7 fractional bits (512 LSBs for Q16.16, 2 for
            /// Q8.8), else `|raw| < 2`.
            pub const fn is_within_zero_tolerance(self) -> bool {
                let () = Self::FORMAT_OK;
                let shift = if FRAC > 7 { FRAC - 7 } else { 1 };
                let tolerance = (1 as $s) << shift;
                self.0 == 0 || (self.0 < tolerance && self.0 > -tolerance)
            }

            /// The bound a quotient by zero saturates to: max for a positive dividend,
            /// min for a negative one, 0 for 0 (C++ `WrapPolicy` division case).
            const fn div_by_zero(dividend: $s) -> Self {
                if dividend > 0 {
                    Self(<$s>::MAX)
                } else if dividend < 0 {
                    Self(<$s>::MIN)
                } else {
                    Self(0)
                }
            }
        }

        impl<const FRAC: u32> Add for QValue<$s, FRAC> {
            type Output = Self;
            fn add(self, rhs: Self) -> Self {
                // C++ adds in the unsigned counterpart to get defined wrap-around;
                // Rust says what it means directly.
                Self(self.0.wrapping_add(rhs.0))
            }
        }

        impl<const FRAC: u32> AddAssign for QValue<$s, FRAC> {
            fn add_assign(&mut self, rhs: Self) {
                *self = *self + rhs;
            }
        }

        impl<const FRAC: u32> Sub for QValue<$s, FRAC> {
            type Output = Self;
            fn sub(self, rhs: Self) -> Self {
                Self(self.0.wrapping_sub(rhs.0))
            }
        }

        impl<const FRAC: u32> Mul for QValue<$s, FRAC> {
            type Output = Self;
            fn mul(self, rhs: Self) -> Self {
                let () = Self::FORMAT_OK;
                // Widen, truncate (arithmetic shift right floors toward -inf), then
                // wrap back to the storage width.
                let product = <$wide>::from(self.0) * <$wide>::from(rhs.0);
                Self((product >> FRAC) as $s)
            }
        }

        impl<const FRAC: u32> Div for QValue<$s, FRAC> {
            type Output = Self;
            fn div(self, rhs: Self) -> Self {
                let () = Self::FORMAT_OK;
                if rhs.0 == 0 {
                    return Self::div_by_zero(self.0);
                }
                // Scale the dividend up by 2^FRAC in the wide type, divide
                // (truncating toward zero, like C++), then wrap back.
                let dividend = <$wide>::from(self.0) * ((1 as $wide) << FRAC);
                Self((dividend / <$wide>::from(rhs.0)) as $s)
            }
        }

        impl<const FRAC: u32> Sqrt for QValue<$s, FRAC> {
            fn sqrt(self) -> Self {
                let () = Self::FORMAT_OK;
                if self.0 <= 0 {
                    return Self(0);
                }
                // n < 2^(storage bits - 1 + FRAC), so it and every sum below fit
                // the wide type, and x stays >= 1.
                let n = <$wide>::from(self.0) << FRAC;
                let mut x = n;
                let mut y = (x + 1) / 2;
                while y < x {
                    x = y;
                    // x >= 1 here, but the compiler cannot prove it; the
                    // fallback is unreachable and keeps the function panic-free.
                    y = (x + n.checked_div(x).unwrap_or(0)) / 2;
                }
                // n < 2^(2 * storage bits - 2), so the root is below 2^(storage
                // bits - 1) and the narrowing (the C++ static_cast) never truncates.
                Self(x as $s)
            }
        }

        impl<const FRAC: u32> Scalar for QValue<$s, FRAC> {
            const ZERO: Self = Self::ZERO;
            const ONE: Self = Self::ONE;
            fn pow2_neg(n: u32) -> Self {
                Self::pow2_neg(n)
            }
            fn div_int(self, n: i32) -> Self {
                self.div_int(n)
            }
            fn mul_round_toward_zero(self, rhs: Self) -> Self {
                self.mul_round_toward_zero(rhs)
            }
            fn mul_round_nearest(self, rhs: Self) -> Self {
                self.mul_round_nearest(rhs)
            }
        }
    };
}

impl_qvalue!(i32, i64);
impl_qvalue!(i16, i32);

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

    /// `sqrt` is the floor of the exact root of `raw << FRAC`: r*r <= n < (r+1)^2.
    fn check_floor_root(raw: i64, frac: u32, root: i64) {
        let n = raw << frac;
        assert!(
            root * root <= n && (root + 1) * (root + 1) > n,
            "raw {raw}: root {root}"
        );
    }

    #[test]
    fn sqrt_every_q8_8_value() {
        for raw in i16::MIN..=i16::MAX {
            let r = i64::from(Q8_8::from_raw(raw).sqrt().raw());
            if raw <= 0 {
                assert_eq!(r, 0);
            } else {
                check_floor_root(i64::from(raw), 8, r);
            }
        }
        assert_eq!(Q8_8::from_int(4).sqrt(), Q8_8::from_int(2));
    }

    #[test]
    fn sqrt_q16_16_sample_and_edges() {
        let mut x: u32 = 1;
        let edges = [1, 2, 3, 65_535, 65_536, 65_537, i32::MAX - 1, i32::MAX];
        for raw in edges.into_iter().chain((0..100_000).map(|_| {
            x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            (x >> 1) as i32
        })) {
            check_floor_root(
                i64::from(raw),
                16,
                i64::from(Q16_16::from_raw(raw).sqrt().raw()),
            );
        }
        assert_eq!(Q16_16::from_int(9).sqrt(), Q16_16::from_int(3));
        assert_eq!(Q16_16::from_int(-9).sqrt(), Q16_16::ZERO);
        // Formats with one integer bit: the root of a value near 1 is near 1 and
        // does not fit; it wraps as the C++ static_cast does, without panicking.
        let _ = QValue::<i32, 31>::from_raw(i32::MAX).sqrt();
        let _ = QValue::<i16, 15>::from_raw(i16::MAX).sqrt();
    }

    #[test]
    fn constants() {
        assert_eq!(Q16_16::ONE.raw(), 65536);
        assert_eq!(Q16_16::from_int(-1).raw(), -65536);
        assert_eq!(Q16_16::pow2_neg(2).raw(), 16384);
        assert_eq!(Q8_8::ONE.raw(), 256);
        assert_eq!(Q8_8::from_int(-1).raw(), -256);
        assert_eq!(Q8_8::pow2_neg(4).raw(), 16);
        assert_eq!((Q8_8::FIXED_BITS, Q8_8::FRACTIONAL_BITS), (8, 8));
    }

    #[test]
    fn from_int_truncates_the_fixed_part() {
        // tinymind's own example (qformat.hpp, applyInteger comment): Q8.8 200 -> -56.
        assert_eq!(Q8_8::from_int(200), Q8_8::from_int(-56));
        assert_eq!(Q8_8::from_int(127).raw(), 127 * 256);
    }

    #[test]
    fn multiply_truncates_toward_negative_infinity() {
        // -1 LSB * 0.5 = -0.5 LSB, which an arithmetic shift floors to -1 LSB.
        let r = Q16_16::from_raw(-1) * Q16_16::pow2_neg(1);
        assert_eq!(r.raw(), -1);
        let r = Q16_16::from_raw(1) * Q16_16::pow2_neg(1);
        assert_eq!(r.raw(), 0);
        assert_eq!((Q8_8::from_raw(-1) * Q8_8::pow2_neg(1)).raw(), -1);
        assert_eq!((Q8_8::from_raw(1) * Q8_8::pow2_neg(1)).raw(), 0);
    }

    #[test]
    fn multiply_wraps_to_the_storage_width() {
        // 100.0 * 2.0 = 200.0 does not fit Q8.8; the product wraps to -56.0.
        let r = Q8_8::from_int(100) * Q8_8::from_int(2);
        assert_eq!(r, Q8_8::from_int(-56));
    }

    #[test]
    fn divide_truncates_toward_zero_and_saturates_on_zero() {
        assert_eq!((Q16_16::from_raw(-3) / Q16_16::from_int(2)).raw(), -1);
        assert_eq!((Q16_16::ONE / Q16_16::ZERO).raw(), i32::MAX);
        assert_eq!((Q16_16::from_int(-1) / Q16_16::ZERO).raw(), i32::MIN);
        assert_eq!((Q16_16::ZERO / Q16_16::ZERO).raw(), 0);
        assert_eq!((Q8_8::from_raw(-3) / Q8_8::from_int(2)).raw(), -1);
        assert_eq!((Q8_8::ONE / Q8_8::ZERO).raw(), i16::MAX);
        assert_eq!((Q8_8::from_int(-1) / Q8_8::ZERO).raw(), i16::MIN);
        assert_eq!(Q8_8::ONE.div_int(0).raw(), i16::MAX);
    }

    #[test]
    fn pow2_neg_range() {
        assert_eq!(Q16_16::pow2_neg(16).raw(), 1);
        assert_eq!(Q16_16::pow2_neg(0), Q16_16::ONE);
        assert_eq!(Q8_8::pow2_neg(8).raw(), 1);
    }

    #[test]
    fn pow2_neg_below_resolution_truncates_to_zero() {
        for n in [17, 20, 32, 63, 64, u32::MAX] {
            assert_eq!(
                Q16_16::pow2_neg(core::hint::black_box(n)),
                Q16_16::ZERO,
                "n = {n}"
            );
        }
        assert_eq!(Q8_8::pow2_neg(9), Q8_8::ZERO);
    }

    #[test]
    fn add_wraps() {
        let r = Q16_16::from_raw(i32::MAX) + Q16_16::from_raw(1);
        assert_eq!(r.raw(), i32::MIN);
        let r = Q8_8::from_raw(i16::MAX) + Q8_8::from_raw(1);
        assert_eq!(r.raw(), i16::MIN);
    }

    #[test]
    fn zero_tolerance() {
        assert!(Q16_16::from_raw(511).is_within_zero_tolerance());
        assert!(Q16_16::from_raw(-511).is_within_zero_tolerance());
        assert!(!Q16_16::from_raw(512).is_within_zero_tolerance());
        assert!(Q8_8::from_raw(1).is_within_zero_tolerance());
        assert!(Q8_8::from_raw(-1).is_within_zero_tolerance());
        assert!(!Q8_8::from_raw(2).is_within_zero_tolerance());
        assert!(!Q8_8::from_raw(-2).is_within_zero_tolerance());
    }
}