f-office-units 0.3.0

Integer lengths and unit conversions for F-Office.
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
use super::{Binary32, Rounding};

/// The bit pattern of binary single precision for a normal `number`.
fn bits(number: Binary32) -> u32 {
    let magnitude = u32::try_from(number.mantissa.unsigned_abs()).unwrap_or(0);
    let sign = u32::from(number.mantissa < 0) << 31;
    // A mantissa of 24 bits holds the hidden bit; the stored exponent counts from the
    // mantissa's top bit with a bias of 127.
    let shift = magnitude.leading_zeros() - 8;
    let exponent = number.exponent + 150 - i32::try_from(shift).unwrap_or(0);
    sign | (u32::try_from(exponent).unwrap_or(0) << 23) | ((magnitude << shift) & 0x007f_ffff)
}

/// The native binary32 number of a normal `number`.
fn native(number: Binary32) -> f32 {
    if number.mantissa == 0 {
        return 0.0;
    }
    f32::from_bits(bits(number))
}

/// A fixed sequence of pseudo-random numbers (`SplitMix64`), so that each run sees the same
/// operands.
struct Sequence(u64);

impl Sequence {
    fn next(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    }

    /// A whole number from 1 to 2^24, which binary32 holds exactly, with either sign when
    /// `signed`.
    fn whole(&mut self, signed: bool) -> i64 {
        let length = 1 + self.next() % 24;
        let value = i64::try_from((self.next() >> (64 - length)).max(1)).unwrap_or(1);
        if signed && self.next() % 2 == 1 {
            -value
        } else {
            value
        }
    }
}

#[test]
fn rounds_a_fraction_to_single_precision_with_whole_numbers() {
    // The bit patterns are those of binary single precision for the same fractions, rounded to
    // the nearest with a tie to the even mantissa.
    let nearest = Binary32::nearest;
    assert_eq!(bits(nearest(333, 1_000)), 0x3eaa_7efa);
    assert_eq!(bits(nearest(45, 100)), 0x3ee6_6666);
    assert_eq!(bits(nearest(7, 1_000)), 0x3be5_6042);
    assert_eq!(bits(nearest(1, 3)), 0x3eaa_aaab);
    assert_eq!(bits(nearest(5, 8)), 0x3f20_0000);
    assert_eq!(bits(nearest(16_777_217, 1)), 0x4b80_0000);
}

#[test]
fn a_zero_numerator_or_denominator_gives_zero() {
    assert_eq!(Binary32::nearest(0, 1_000), Binary32::ZERO);
    assert_eq!(Binary32::nearest(1, 0), Binary32::ZERO);
}

#[test]
fn a_carry_out_of_the_mantissa_gives_the_next_power_of_two() {
    // 2^24 - 1/2 lies halfway between 2^24 - 1 and 2^24, and the tie goes to the even one.
    let carried = Binary32::nearest((1 << 25) - 1, 2);
    assert_eq!((carried.mantissa(), carried.exponent()), (1 << 23, 1));
    assert_eq!(bits(carried), 0x4b80_0000);
    // Paint's former model of the page coordinates overflowed here.
    assert_eq!(carried, Binary32::nearest(1 << 24, 1));
}

#[test]
fn adds_in_single_precision_with_whole_numbers() {
    let nearest = Binary32::nearest;
    assert_eq!(
        bits(nearest(722, 1_000).plus(nearest(611, 1_000))),
        0x3faa_9fbe
    );
    assert_eq!(bits(nearest(33, 100).plus(nearest(45, 100))), 0x3f47_ae14);
    assert_eq!(bits(nearest(1, 10).plus(nearest(2, 10))), 0x3e99_999a);
    assert_eq!(bits(nearest(1, 1_000).plus(nearest(-1, 1))), 0xbf7f_be77);
}

#[test]
fn compares_differences_of_sums_with_a_fraction() {
    let nearest = Binary32::nearest;
    // 0.1 and 0.2 in single precision sum to more than 0.3; 0.333 less 0.33 is under 0.003.
    let sum = nearest(1, 10).plus(nearest(2, 10));
    assert!(sum.differs_by(Binary32::ZERO, 3, 10));
    assert!(!nearest(333, 1_000).differs_by(nearest(33, 100), 3, 1_000));
    assert!(nearest(833, 1_000).differs_by(nearest(83, 100), 3, 1_000));
    // A number less itself is zero, with the exponent of zero.
    assert_eq!(nearest(1, 3).minus(nearest(1, 3)), Binary32::ZERO);
}

#[test]
fn rounds_to_whole_numbers_at_signed_halves_and_small_values() {
    let nearest = Binary32::nearest;
    for (top, bottom, lower, higher, toward_zero) in [
        (13, 2, 6, 7, 6),
        (-13, 2, -7, -6, -6),
        (12, 2, 6, 6, 6),
        (1, 1_i128 << 80, 0, 0, 0),
        (-1, 1_i128 << 80, 0, 0, 0),
        (1_i128 << 40, 1, 1_i64 << 40, 1_i64 << 40, 1_i64 << 40),
    ] {
        let number = nearest(top, bottom);
        assert_eq!(number.whole(true), lower);
        assert_eq!(number.whole(false), higher);
        assert_eq!(number.toward_zero(), toward_zero);
    }
    assert!(nearest(-3, 10).reaches(nearest(3, 10)));
    assert!(!nearest(29, 100).reaches(nearest(-3, 10)));
}

/// Each operation on the fractions `left` and `right` and the factor against native binary32.
// The native numbers are the reference that the whole numbers must give, and whole numbers up
// to 2^24 are exact in binary32.
#[allow(clippy::float_arithmetic, clippy::cast_precision_loss)]
fn compare_with_native(left: (i64, i64), right: (i64, i64), factor: i64) {
    let case = format!("{left:?} and {right:?}, factor {factor}");
    // Both operands of a native division are exact, so the processor rounds the quotient once,
    // as `nearest` does.
    let first = Binary32::nearest(left.0.into(), left.1.into());
    let second = Binary32::nearest(right.0.into(), right.1.into());
    let (one, other) = (native(first), native(second));
    assert_eq!(one, left.0 as f32 / left.1 as f32, "{case}");
    assert_eq!(native(first.plus(second)), one + other, "{case}");
    assert_eq!(native(first.minus(second)), one - other, "{case}");
    assert_eq!(native(first.times(factor)), one * factor as f32, "{case}");
    assert_eq!(native(first.over(second)), one / other, "{case}");
}

#[test]
fn agrees_with_native_binary32_on_random_operands() {
    let mut sequence = Sequence(0xB32);
    for _ in 0..200_000 {
        let left = (sequence.whole(true), sequence.whole(false));
        let right = (sequence.whole(true), sequence.whole(false));
        compare_with_native(left, right, sequence.whole(true));
    }
}

/// The former `Binary32::nearest`, kept only as the oracle of the form with one division. It
/// scaled the fraction by one bit at a time, with a 128-bit division at each step, until the
/// quotient had two bits more than a mantissa. Its shifts keep every bit for a denominator of
/// fewer than [`ORACLE_DENOMINATOR_BITS`] bits, the range of each comparison below: it stops at
/// a shifted numerator below 2^(BITS + 2) times the denominator, which is then below 2^128.
/// Beyond that range a shift can lose bits, and the loop need not end. The form with one
/// division shifts no further than this loop did, so it keeps every bit wherever the loop did.
/// Its last shift, `quotient << 1`, drops the top bit of the quotient 2^127 of `i128::MIN` over
/// 1 and gives zero there, so no comparison takes that fraction: a test of its own checks it.
fn nearest_by_steps(numerator: i128, denominator: i128) -> Binary32 {
    if numerator == 0 || denominator <= 0 {
        return Binary32::ZERO;
    }
    let mut exponent = 0;
    let (mut top, bottom) = (numerator.unsigned_abs(), denominator.unsigned_abs());
    while top / bottom < (1 << (Binary32::BITS + 1)) {
        top <<= 1;
        exponent -= 1;
    }
    let quotient = top / bottom;
    let rest = top % bottom;
    let sticky = u128::from(rest != 0);
    Binary32::rounded(
        (quotient << 1) | sticky,
        exponent - 1,
        numerator < 0,
        Rounding::Nearest,
    )
}

/// The oracle keeps every bit for a denominator below 2^102 ([`nearest_by_steps`]).
const ORACLE_DENOMINATOR_BITS: u32 = 102;

/// The numerators that the callers of `nearest` pass are below 2^88: `single` of
/// `f-office-paint` takes a quotient below 2^24 over a denominator of at most 2^64, the power of
/// two of a single-precision fraction (`single_less` and `held`). The writer counts of
/// `f-office-docx` (`grid.rs`) pass `i64` lengths, and `over` passes mantissas below 2^24.
const CALLERS_NUMERATOR_BITS: u32 = 88;

/// The denominators that the callers of `nearest` pass are below 2^73: the writer counts of
/// `f-office-docx` (`grid.rs`) divide by an em of `THOUSANDTHS` (1,000) times an `i64` size.
const CALLERS_DENOMINATOR_BITS: u32 = 73;

/// Checks that the form with one division gives the oracle's number for the fraction.
fn same_as_steps(numerator: i128, denominator: i128) {
    assert_eq!(
        Binary32::nearest(numerator, denominator),
        nearest_by_steps(numerator, denominator),
        "{numerator}/{denominator}"
    );
}

/// A whole number of 1 to `bits` bits, of a random length and with random bits below its top
/// bit.
fn of_bits(sequence: &mut Sequence, bits: u32) -> i128 {
    let length = 1 + u32::try_from(sequence.next() % u64::from(bits)).unwrap_or(0);
    let random = (u128::from(sequence.next()) << 64) | u128::from(sequence.next());
    let value = (random >> (128 - length)) | (1 << (length - 1));
    i128::try_from(value).unwrap_or(1)
}

/// A random sign for `value`.
fn signed(sequence: &mut Sequence, value: i128) -> i128 {
    if sequence.next() % 2 == 1 {
        -value
    } else {
        value
    }
}

#[test]
fn one_division_gives_the_steps_number_of_every_small_fraction() {
    for numerator in -1_024..=1_024 {
        for denominator in 1..=1_024 {
            same_as_steps(numerator, denominator);
        }
    }
}

#[test]
fn one_division_gives_the_steps_number_at_powers_of_two_and_their_neighbours() {
    // The numerators go up to the largest `i128`, beyond the callers', and the denominators up
    // to the oracle's range, beyond the callers'.
    const {
        assert!(CALLERS_DENOMINATOR_BITS < ORACLE_DENOMINATOR_BITS);
        assert!(CALLERS_NUMERATOR_BITS < i128::BITS);
    }
    let around = |bits: u32| -> Vec<i128> {
        let mut values: Vec<i128> = (0..bits)
            .flat_map(|power| {
                let value = 1_i128 << power;
                [value - 1, value, value + 1]
            })
            .filter(|value| *value > 0)
            .collect();
        values.dedup();
        values
    };
    let mut numerators = around(i128::BITS - 1);
    numerators.push(i128::MAX);
    let denominators = around(ORACLE_DENOMINATOR_BITS - 1);
    for &numerator in &numerators {
        for &denominator in &denominators {
            same_as_steps(numerator, denominator);
            same_as_steps(-numerator, denominator);
        }
    }
}

/// The mantissa and the exponent of `mantissa * 2^exponent` for a mantissa of 24 bits or of
/// 2^24, which carries into the next power of two.
fn carried(mantissa: i128, exponent: i32) -> (i64, i32) {
    if mantissa == 1 << 24 {
        (1 << 23, exponent + 1)
    } else {
        (i64::try_from(mantissa).unwrap_or(0), exponent)
    }
}

/// Checks the tie `factor * (2m + 1) / (factor * 2^(j + 1))`, halfway between the mantissas m
/// and m + 1 at the exponent -j, and the numerators one unit above and below it, against the
/// even mantissa, m + 1 and m, and against the oracle, with both signs.
fn check_tie(m: i128, factor: i128, j: u32) {
    let numerator = factor * (2 * m + 1);
    let denominator = factor << (j + 1);
    let at = |numerator| {
        let near = Binary32::nearest(numerator, denominator);
        (near.mantissa(), near.exponent())
    };
    let exponent = -j.cast_signed();
    let even = if m % 2 == 0 { m } else { m + 1 };
    let case = format!("{m} {factor} {j}");
    assert_eq!(at(numerator), carried(even, exponent), "{case}");
    assert_eq!(at(numerator - 1), carried(m, exponent), "{case}");
    assert_eq!(at(numerator + 1), carried(m + 1, exponent), "{case}");
    for near in [numerator - 1, numerator, numerator + 1] {
        same_as_steps(near, denominator);
        same_as_steps(-near, denominator);
    }
}

#[test]
fn one_division_gives_the_steps_number_at_ties_and_one_unit_beside_them() {
    // An odd factor above and below keeps a tie a tie.
    let mut sequence = Sequence(0x71E);
    let mut mantissas: Vec<i128> = vec![1 << 23, (1 << 23) + 1, (1 << 24) - 2, (1 << 24) - 1];
    mantissas.extend((0..60).map(|_| (1 << 23) + i128::from(sequence.next() >> 41)));
    for m in mantissas {
        for factor in [1, 3, 5, 999, 1_000_001] {
            for j in [0, 1, 24, 40, 60] {
                check_tie(m, factor, j);
            }
        }
    }
}

#[test]
fn a_denominator_that_is_not_positive_gives_zero_in_both_forms() {
    for numerator in [i128::MIN + 1, -5, -1, 0, 1, 7, i128::MAX] {
        for denominator in [i128::MIN, -3, -1, 0] {
            assert_eq!(Binary32::nearest(numerator, denominator), Binary32::ZERO);
            same_as_steps(numerator, denominator);
        }
    }
}

#[test]
fn one_division_gives_the_steps_number_on_random_fractions_of_the_callers_range() {
    let mut sequence = Sequence(0x0D1F);
    for _ in 0..200_000 {
        let numerator = of_bits(&mut sequence, CALLERS_NUMERATOR_BITS);
        let numerator = signed(&mut sequence, numerator);
        let denominator = of_bits(&mut sequence, CALLERS_DENOMINATOR_BITS);
        same_as_steps(numerator, denominator);
    }
}

#[test]
fn one_division_gives_the_steps_number_on_random_fractions_of_any_numerator() {
    // Numerators of up to 127 bits, beyond the callers', over denominators of the oracle's
    // range: a numerator of many more bits than its denominator scales by a negative power of
    // two.
    let mut sequence = Sequence(0x7F);
    for _ in 0..100_000 {
        let numerator = of_bits(&mut sequence, i128::BITS - 1);
        let numerator = signed(&mut sequence, numerator);
        let denominator = of_bits(&mut sequence, ORACLE_DENOMINATOR_BITS - 1);
        same_as_steps(numerator, denominator);
    }
}

#[test]
fn the_scaled_quotient_has_one_or_two_bits_more_than_a_mantissa_for_any_top() {
    // A `top` of more than `BITS + 1` bits more than its `bottom`, such as 2^40 over 1, needs a
    // negative scale.
    let mantissa = 1_u128 << Binary32::BITS;
    let mut fractions: Vec<(u128, u128)> = vec![
        (1 << 40, 1),
        (1 << 127, 1),
        ((1 << 127) - 1, 1),
        (1 << 127, 3),
        (1, 1),
        (1, (1 << 127) - 1),
    ];
    let mut sequence = Sequence(0x5CA1E);
    fractions.extend((0..20_000).map(|_| {
        let top = of_bits(&mut sequence, i128::BITS - 1).cast_unsigned();
        (top, of_bits(&mut sequence, i128::BITS - 1).cast_unsigned())
    }));
    for (top, bottom) in fractions {
        let (quotient, _, _) = super::scaled_quotient(top, bottom);
        assert!(
            (mantissa..mantissa << 2).contains(&quotient),
            "{top}/{bottom}: {quotient}"
        );
    }
}

#[test]
fn the_most_negative_numerator_over_one_keeps_the_top_bit_of_its_quotient() {
    // The quotient of `i128::MIN` over 1 is 2^127, whose top bit a shift by one place drops,
    // and both former forms gave zero for it. Binary32 holds
    // -2^127 exactly.
    let near = Binary32::nearest(i128::MIN, 1);
    assert_eq!((near.mantissa(), near.exponent()), (-(1 << 23), 104));
    assert_eq!(bits(near), 0xff00_0000);
    // Over a larger denominator the quotient is below 2^127, and the oracle holds.
    for denominator in 2..=1_024 {
        same_as_steps(i128::MIN, denominator);
    }
}

#[test]
fn a_denominator_of_2_to_the_103_or_more_takes_its_bits_by_long_division() {
    // Beyond the oracle's range the shift would lose bits. The number of a fraction with both
    // parts scaled by one power of two is the same, and a denominator scaled alone moves the
    // exponent.
    let mut sequence = Sequence(0x103);
    for _ in 0..2_000 {
        let numerator = of_bits(&mut sequence, 60);
        let numerator = signed(&mut sequence, numerator);
        let denominator = of_bits(&mut sequence, 60);
        let near = Binary32::nearest(numerator, denominator);
        let length = denominator.cast_unsigned().bit_width();
        for by in [104 - length, i128::BITS - 1 - length] {
            let far = denominator << by;
            assert!(far >= 1 << 103);
            let moved = Binary32 {
                exponent: near.exponent - i32::try_from(by).unwrap_or(0),
                ..near
            };
            assert_eq!(
                Binary32::nearest(numerator, far),
                moved,
                "{numerator}/{far}"
            );
            if let Some(both) = numerator.checked_shl(by).filter(|n| n >> by == numerator) {
                assert_eq!(Binary32::nearest(both, far), near, "{both}/{far}");
            }
        }
    }
}

/// The exact value of `number` as a fraction with a positive denominator, for an exponent
/// from -100 to 60 and a mantissa below 2^24.
fn exact(number: Binary32) -> (i128, i128) {
    let mantissa = i128::from(number.mantissa);
    let by = number.exponent.unsigned_abs();
    if number.exponent >= 0 {
        (mantissa << by, 1)
    } else {
        (mantissa, 1 << by)
    }
}

/// Whether `number` lies at or below `numerator / denominator`, for a positive denominator.
fn at_or_below(number: Binary32, numerator: i128, denominator: i128) -> bool {
    let (top, bottom) = exact(number);
    top * denominator <= numerator * bottom
}

/// The number one place below a number whose mantissa has 24 bits, as every nonzero result of
/// `nearest` has.
fn next_below(number: Binary32) -> Binary32 {
    let (mantissa, exponent) = (number.mantissa, number.exponent);
    let top = 1 << (Binary32::BITS - 1);
    let (mantissa, exponent) = if mantissa == top {
        ((1 << Binary32::BITS) - 1, exponent - 1)
    } else if mantissa == -((1 << Binary32::BITS) - 1) {
        (-top, exponent + 1)
    } else {
        (mantissa - 1, exponent)
    };
    Binary32 { mantissa, exponent }
}

/// The oracle of `below`: the nearest number, or the number below it when the nearest lies
/// above the fraction. It shares no rounding code with `below`.
fn below_by_nearest(numerator: i128, denominator: i128) -> Binary32 {
    let near = nearest_by_steps(numerator, denominator);
    if numerator == 0 || at_or_below(near, numerator, denominator) {
        near
    } else {
        next_below(near)
    }
}

/// Checks `below` against its oracle, and that the number lies at or below the fraction and the
/// one above it does not.
fn check_below(numerator: i128, denominator: i128) {
    let below = Binary32::below(numerator, denominator);
    assert_eq!(
        below,
        below_by_nearest(numerator, denominator),
        "{numerator}/{denominator}"
    );
    assert!(at_or_below(below, numerator, denominator));
}

#[test]
fn rounds_a_fraction_down_to_single_precision() {
    // The bit patterns of binary single precision for the same fractions, rounded toward
    // negative infinity: one place below the nearest where the nearest rounds up.
    for (numerator, denominator, pattern) in [
        (1, 3, 0x3eaa_aaaa),
        (-1, 3, 0xbeaa_aaab),
        (2, 3, 0x3f2a_aaaa),
        (5, 8, 0x3f20_0000),
        (16_777_217, 1, 0x4b80_0000),
        (-16_777_217, 1, 0xcb80_0001),
    ] {
        let below = Binary32::below(numerator, denominator);
        assert_eq!(bits(below), pattern, "{numerator}/{denominator}");
    }
    assert_eq!(bits(Binary32::nearest(1, 3)), 0x3eaa_aaab);
    assert_eq!(Binary32::below(0, 3), Binary32::ZERO);
    assert_eq!(Binary32::below(1, 0), Binary32::ZERO);
}

#[test]
fn below_gives_the_largest_number_at_or_below_every_small_fraction() {
    for numerator in -512..=512 {
        for denominator in 1..=512 {
            check_below(numerator, denominator);
        }
    }
}

#[test]
fn below_gives_the_largest_number_at_or_below_random_fractions() {
    let mut sequence = Sequence(0xb310);
    for _ in 0..20_000 {
        let numerator = of_bits(&mut sequence, 40);
        let numerator = signed(&mut sequence, numerator);
        check_below(numerator, of_bits(&mut sequence, 40));
    }
}

/// A random number of either sign from 2^-20 to 2^20, with a mantissa of 24 bits.
fn operand(sequence: &mut Sequence) -> Binary32 {
    let numerator = of_bits(sequence, 40);
    let numerator = signed(sequence, numerator);
    let denominator = 1 << (sequence.next() % 40);
    Binary32::nearest(numerator, denominator)
}

#[test]
fn each_operation_below_rounds_its_exact_result_down() {
    // Each operation rounds the exact result once, so it gives what `below` gives for that
    // result as a fraction.
    let mut sequence = Sequence(0xd0e5);
    for _ in 0..20_000 {
        let (left, right) = (operand(&mut sequence), operand(&mut sequence));
        let ((left_top, left_bottom), (right_top, right_bottom)) = (exact(left), exact(right));
        let product = Binary32::below(left_top * right_top, left_bottom * right_bottom);
        let product_below = left.product_below(right);
        assert_eq!(product_below, product, "{left:?} * {right:?}");
        let sign = right_top.signum();
        let quotient = Binary32::below(
            left_top * right_bottom * sign,
            left_bottom * right_top * sign,
        );
        let over_below = left.over_below(right);
        assert_eq!(over_below, quotient, "{left:?} / {right:?}");
        let bottom = left_bottom.max(right_bottom);
        let sum = left_top * (bottom / left_bottom) + right_top * (bottom / right_bottom);
        let plus_below = left.plus_below(right);
        assert_eq!(
            plus_below,
            Binary32::below(sum, bottom),
            "{left:?} + {right:?}"
        );
        let factor = of_bits(&mut sequence, 30);
        let factor = i64::try_from(signed(&mut sequence, factor)).unwrap_or(1);
        let times = Binary32::below(left_top * i128::from(factor), left_bottom);
        let times_below = left.times_below(factor);
        assert_eq!(times_below, times, "{left:?} * {factor}");
    }
}

#[test]
fn a_sum_with_a_far_smaller_number_rounds_down_as_the_exact_sum() {
    // The two exponents differ by more than 64, so the smaller number only decides the
    // direction: the larger number itself, or the number one place below it.
    let three = Binary32::nearest(3, 1);
    let tiny = Binary32::nearest(1, 1 << 100);
    let minus = |number: Binary32| Binary32 {
        mantissa: -number.mantissa,
        ..number
    };
    assert_eq!(three.plus_below(tiny), three);
    assert_eq!(tiny.plus_below(three), three);
    assert_eq!(three.plus_below(minus(tiny)), next_below(three));
    assert_eq!(minus(three).plus_below(tiny), minus(three));
    assert_eq!(
        minus(three).plus_below(minus(tiny)),
        next_below(minus(three))
    );
    assert_eq!(three.plus_below(Binary32::ZERO), three);
    assert_eq!(Binary32::ZERO.plus_below(tiny), tiny);
}

#[test]
fn the_floor_is_the_largest_whole_number_at_or_below() {
    let nearest = Binary32::nearest;
    for (top, bottom, floor) in [
        (13, 2, 6),
        (-13, 2, -7),
        (12, 2, 6),
        (-5, 1, -5),
        (1, 1_i128 << 80, 0),
        (-1, 1_i128 << 80, -1),
        (1_i128 << 40, 1, 1_i64 << 40),
        (0, 1, 0),
    ] {
        assert_eq!(nearest(top, bottom).floor(), floor, "{top}/{bottom}");
    }
}

/// Whether `number` has the one form of its value: zero, or a mantissa of exactly 24 bits.
fn in_one_form(number: Binary32) -> bool {
    let mantissa = number.mantissa.unsigned_abs();
    number == Binary32::ZERO || (1 << (Binary32::BITS - 1)..1 << Binary32::BITS).contains(&mantissa)
}

#[test]
fn each_number_has_one_form() {
    // A difference of two near numbers has fewer bits than a mantissa. In its one form it
    // equals the same number made by a division.
    let nearest = Binary32::nearest;
    assert_eq!(nearest(3, 1).minus(nearest(2, 1)), nearest(1, 1));
    assert_eq!(nearest(1, 3).minus(nearest(1, 3)), Binary32::ZERO);
    let mut sequence = Sequence(0x0f0e);
    for _ in 0..20_000 {
        let (left, right) = (operand(&mut sequence), operand(&mut sequence));
        let factor = of_bits(&mut sequence, 30);
        let factor = i64::try_from(signed(&mut sequence, factor)).unwrap_or(1);
        for result in [
            left.plus(right),
            left.minus(right),
            left.minus(next_below(left)),
            left.plus_below(right),
            left.times(factor),
            left.times_below(factor),
            left.product_below(right),
            left.over(right),
            left.over_below(right),
        ] {
            assert!(
                in_one_form(result),
                "{left:?} {right:?} {factor}: {result:?}"
            );
        }
    }
}

/// The negative of `number`.
fn negative(number: Binary32) -> Binary32 {
    Binary32 {
        mantissa: -number.mantissa,
        ..number
    }
}

/// The exponent gaps of the tests of a far smaller number: at 64 or more, the larger number
/// stays and the smaller one decides only the rounding or the comparison.
const FAR_GAPS: [i32; 3] = [64, 65, 100];

/// 1, 2^gap and 2^-gap.
fn far(gap: i32) -> (Binary32, Binary32, Binary32) {
    let nearest = Binary32::nearest;
    let (one, large, tiny) = (nearest(1, 1), nearest(1 << gap, 1), nearest(1, 1 << gap));
    let gaps = (large.exponent - one.exponent, one.exponent - tiny.exponent);
    assert_eq!(gaps, (gap, gap));
    (one, large, tiny)
}

#[test]
fn a_sum_with_a_far_smaller_number_keeps_the_larger_one() {
    for gap in FAR_GAPS {
        let (one, large, _) = far(gap);
        let sums = [
            large.plus(one),
            one.plus(large),
            large.minus(one),
            large.plus_below(one),
            large.plus_below(negative(one)),
        ];
        let expected = [large, large, large, large, next_below(large)];
        assert_eq!(sums, expected, "{gap}");
        let order = (large.reaches(one), one.reaches(large));
        assert_eq!(order, (true, false), "{gap}");
    }
}

/// The largest part of a limit of [`Binary32::differs_by`], 2^32 - 1.
const MOST: i64 = (1 << 32) - 1;

#[test]
fn differs_by_counts_a_far_smaller_number() {
    // 1 less 2^-gap lies below 1 and above every other fraction of two `u32` parts below 1,
    // and 1 plus 2^-gap lies above 1 and below every other one above it.
    for gap in FAR_GAPS {
        let (one, large, tiny) = far(gap);
        let answers = [
            large.differs_by(one, 1, 1),
            one.differs_by(tiny, 1, 1),
            tiny.differs_by(one, 1, 1),
            one.differs_by(tiny, MOST - 1, MOST),
            tiny.differs_by(one, MOST - 1, MOST),
            one.differs_by(tiny, 999, 1_000),
            one.differs_by(negative(tiny), 1, 1),
            one.differs_by(negative(tiny), MOST, MOST - 1),
        ];
        let expected = [true, false, false, true, true, true, true, false];
        assert_eq!(answers, expected, "{gap}");
    }
}

#[test]
fn differs_by_counts_a_negative_numerator_by_its_magnitude_up_to_its_range() {
    let (one, zero) = (Binary32::nearest(1, 1), Binary32::ZERO);
    let answers = [
        one.differs_by(zero, -1, 1),
        one.differs_by(zero, -2, 1),
        one.differs_by(zero, MOST, MOST),
        one.differs_by(zero, -MOST, 1),
    ];
    assert_eq!(answers, [true, false, true, false]);
}

#[test]
fn differs_by_stops_a_debug_build_at_parts_outside_its_range() {
    // A denominator that is not positive and a part of 2^32 or more: a debug build stops, and
    // a release build gives `false`.
    let (one, zero) = (Binary32::nearest(1, 1), Binary32::ZERO);
    let release = (!cfg!(debug_assertions)).then_some(false);
    for (numerator, denominator) in [(1, 0), (1, -1), (0, MOST + 1), (MOST + 1, MOST + 1)] {
        let answer = std::panic::catch_unwind(|| one.differs_by(zero, numerator, denominator));
        assert_eq!(answer.ok(), release, "{numerator}/{denominator}");
    }
}

#[test]
fn differs_by_compares_the_exact_difference_with_the_exact_fraction() {
    // Random operands and limits, and the two limits next to each difference with the same
    // denominator, against exact arithmetic.
    let mut sequence = Sequence(0x0d1f);
    for _ in 0..20_000 {
        let (left, right) = (operand(&mut sequence), operand(&mut sequence));
        let ((left_top, left_bottom), (right_top, right_bottom)) = (exact(left), exact(right));
        let bottom = left_bottom.max(right_bottom);
        let difference =
            (left_top * (bottom / left_bottom) - right_top * (bottom / right_bottom)).abs();
        let denominator = u32::try_from(sequence.next() >> 40).unwrap_or(1).max(1);
        let random = u32::try_from(sequence.next() >> 32).unwrap_or(0);
        let next = difference * i128::from(denominator) / bottom;
        let mut limits = vec![random];
        limits.extend(
            [next, next + 1]
                .into_iter()
                .filter_map(|n| u32::try_from(n).ok()),
        );
        for numerator in limits {
            let exact = difference * i128::from(denominator) >= i128::from(numerator) * bottom;
            assert_eq!(
                left.differs_by(right, numerator.into(), denominator.into()),
                exact,
                "{left:?} {right:?} {numerator}/{denominator}"
            );
        }
    }
}

#[test]
fn a_whole_number_beyond_an_i64_saturates() {
    // 2^127 is a number of the type; its whole number is the largest `i64`, and the whole
    // number of its negative the smallest.
    let nearest = Binary32::nearest;
    let top = nearest(i128::MAX, 1);
    assert_eq!((top.mantissa, top.exponent), (1 << 23, 104));
    for (number, whole) in [
        (top, i64::MAX),
        (nearest(-i128::MAX, 1), i64::MIN),
        (nearest(1 << 63, 1), i64::MAX),
        (nearest(-(1 << 63), 1), i64::MIN),
        (nearest((1 << 63) - (1 << 39), 1), i64::MAX - (1 << 39) + 1),
    ] {
        for rounded in [
            number.whole(false),
            number.whole(true),
            number.floor(),
            number.toward_zero(),
        ] {
            assert_eq!(rounded, whole, "{number:?}");
        }
    }
}