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
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
// Copyright © 2026 Mikhail Hogrefe
//
// Uses code adopted from the GNU MPFR Library.
//
// Copyright © 1999-2025 Free Software Foundation, Inc.
//
// This file is part of Malachite.
//
// Malachite is free software: you can redistribute it and/or modify it under the terms of the GNU
// Lesser General Public License (LGPL) as published by the Free Software Foundation; either version
// 3 of the License, or (at your option) any later version. See <https://www.gnu.org/licenses/>.
use crate::emulate_float_to_float_fn;
use malachite_base::num::basic::floats::PrimitiveFloat;
use crate::Float;
use crate::InnerFloat::{Finite, Infinity, Zero};
use core::cmp::Ordering::{self, *};
use malachite_base::num::arithmetic::traits::{IsPowerOf2, NegModPowerOf2, PowerOf2};
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::conversion::traits::{ExactFrom, IsInteger};
use malachite_base::num::logic::traits::{LowMask, SignificantBits};
use malachite_base::rounding_modes::RoundingMode::{self, *};
use malachite_nz::natural::Natural;
use malachite_nz::natural::arithmetic::float::round::{
limbs_float_round_to_integer, with_float_significand_limbs,
};
use malachite_nz::platform::Limb;
// One with the given sign, at the given precision.
fn signed_one(sign: bool, prec: u64) -> Float {
Float(Finite {
sign,
exponent: 1,
precision: prec,
significand: Natural::power_of_2(prec.neg_mod_power_of_2(Limb::LOG_WIDTH) + prec - 1),
})
}
impl Float {
// This is mpfr_rint from rint.c, MPFR 4.2.2, with the result's precision passed explicitly and
// with MPFR_RNDNA (round to nearest, ties away from zero) selected by the `ties_away` flag
// alongside `Nearest` rather than by a distinct rounding mode. Returns the rounded value, an
// `Ordering` comparing it to the exact input, and whether the input was an integer; the pair is
// a bijection with MPFR's refined ternary. The rounding is a single rounding to an integer
// representable at `prec`: no double rounding is performed.
// The maximum finite value with the given sign at the given precision, for overflow in the
// directed modes that cannot produce an infinity.
fn max_finite(sign: bool, prec: u64) -> Self {
Self(Finite {
sign,
exponent: Self::MAX_EXPONENT,
precision: prec,
significand: Natural::low_mask(prec) << prec.neg_mod_power_of_2(Limb::LOG_WIDTH),
})
}
fn round_to_integer_then_helper(
&self,
irm: RoundingMode,
ties_away: bool,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering) {
if !matches!(self, Self(Finite { .. })) || self.is_integer() {
return Self::from_float_prec_round_ref(self, prec, rm);
}
// Rounding to an integer at self's own precision is exact, unless the carry at the maximum
// exponent overflows.
let t = self
.round_to_integer_helper(self.significant_bits(), irm, ties_away)
.0;
if let Self(Infinity { sign }) = t {
// The integer exceeds the exponent range; apply the final rounding mode's overflow
// behavior, as mpfr_overflow does.
let away = match rm {
Floor => !sign,
Ceiling => sign,
Down => false,
Up | Nearest => true,
Exact => panic!("overflow in round_to_integer_then with the Exact mode"),
};
return if away {
(t, if sign { Greater } else { Less })
} else {
(
Self::max_finite(sign, prec),
if sign { Less } else { Greater },
)
};
}
Self::from_float_prec_round(t, prec, rm)
}
/// Rounds a [`Float`] to an integer, representable at the specified precision, in the direction
/// given by the specified rounding mode. An [`Ordering`] comparing the result to the exact
/// input is also returned, along with a `bool` indicating whether the input was an integer. The
/// [`Float`] is taken by value.
///
/// The result is produced by a single rounding to an integer representable at the target
/// precision: if the input's integer part needs more bits than the precision provides, no
/// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
/// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. The rounding mode
/// gives the integer-rounding direction: `Floor` and `Ceiling` are the floor and ceiling
/// functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest` rounds to the
/// nearest integer with ties to even. `Exact` is not allowed.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero or if `rm` is `Exact`.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(4, Floor),
/// (Float::TWO, Less, false)
/// );
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(4, Ceiling),
/// (Float::from(3u32), Greater, false)
/// );
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(4, Nearest),
/// (Float::TWO, Less, false)
/// );
///
/// // A single rounding: the nearest integer to 10.5 representable at 2 bits is 12.
/// let x = Float::from(10.5f64);
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(2, Nearest),
/// (Float::from(12u32), Greater, false)
/// );
///
/// // 7 is an integer, but needs rounding to fit 2 bits.
/// let x = Float::from(7u32);
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(2, Nearest),
/// (Float::from(8u32), Greater, true)
/// );
/// ```
#[inline]
pub fn round_to_integer_prec_round(
self,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering, bool) {
self.round_to_integer_helper(prec, rm, false)
}
/// Rounds a [`Float`] to an integer, representable at the specified precision, in the direction
/// given by the specified rounding mode. An [`Ordering`] comparing the result to the exact
/// input is also returned, along with a `bool` indicating whether the input was an integer. The
/// [`Float`] is taken by reference.
///
/// The result is produced by a single rounding to an integer representable at the target
/// precision: if the input's integer part needs more bits than the precision provides, no
/// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
/// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. The rounding mode
/// gives the integer-rounding direction: `Floor` and `Ceiling` are the floor and ceiling
/// functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest` rounds to the
/// nearest integer with ties to even. `Exact` is not allowed.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero or if `rm` is `Exact`.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(4, Floor),
/// (Float::TWO, Less, false)
/// );
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(4, Ceiling),
/// (Float::from(3u32), Greater, false)
/// );
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(4, Nearest),
/// (Float::TWO, Less, false)
/// );
///
/// // A single rounding: the nearest integer to 10.5 representable at 2 bits is 12.
/// let x = Float::from(10.5f64);
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(2, Nearest),
/// (Float::from(12u32), Greater, false)
/// );
///
/// // 7 is an integer, but needs rounding to fit 2 bits.
/// let x = Float::from(7u32);
/// assert_eq!(
/// x.round_to_integer_prec_round_ref(2, Nearest),
/// (Float::from(8u32), Greater, true)
/// );
/// ```
#[inline]
pub fn round_to_integer_prec_round_ref(
&self,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering, bool) {
self.round_to_integer_helper(prec, rm, false)
}
/// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
/// ties going to even. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by value.
///
/// The result is produced by a single rounding to an integer representable at the target
/// precision: if the input's integer part needs more bits than the precision provides, no
/// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
/// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_float::Float;
///
/// let x = Float::from(2.5f64);
/// assert_eq!(x.round_to_integer_prec_ref(4), (Float::TWO, Less, false));
/// assert_eq!(
/// Float::from(4u32).round_to_integer_prec(2),
/// (Float::from(4u32), Equal, true)
/// );
/// ```
#[inline]
pub fn round_to_integer_prec(self, prec: u64) -> (Self, Ordering, bool) {
self.round_to_integer_helper(prec, Nearest, false)
}
/// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
/// ties going to even. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by reference.
///
/// The result is produced by a single rounding to an integer representable at the target
/// precision: if the input's integer part needs more bits than the precision provides, no
/// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
/// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_float::Float;
///
/// let x = Float::from(2.5f64);
/// assert_eq!(x.round_to_integer_prec_ref(4), (Float::TWO, Less, false));
/// assert_eq!(
/// Float::from(4u32).round_to_integer_prec(2),
/// (Float::from(4u32), Equal, true)
/// );
/// ```
#[inline]
pub fn round_to_integer_prec_ref(&self, prec: u64) -> (Self, Ordering, bool) {
self.round_to_integer_helper(prec, Nearest, false)
}
/// Rounds a [`Float`] to an integer, representable at the input's own precision, in the
/// direction given by the specified rounding mode. An [`Ordering`] comparing the result to the
/// exact input is also returned, along with a `bool` indicating whether the input was an
/// integer. The [`Float`] is taken by value.
///
/// The rounding mode gives the integer-rounding direction: `Floor` and `Ceiling` are the floor
/// and ceiling functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest`
/// rounds to the nearest integer with ties to even. `Exact` is not allowed.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `rm` is `Exact`.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_round_ref(Ceiling),
/// (Float::from(3u32), Greater, false)
/// );
/// assert_eq!(
/// x.round_to_integer_round_ref(Floor),
/// (Float::TWO, Less, false)
/// );
/// ```
#[inline]
pub fn round_to_integer_round(self, rm: RoundingMode) -> (Self, Ordering, bool) {
self.round_to_integer_helper(self.significant_bits(), rm, false)
}
/// Rounds a [`Float`] to an integer, representable at the input's own precision, in the
/// direction given by the specified rounding mode. An [`Ordering`] comparing the result to the
/// exact input is also returned, along with a `bool` indicating whether the input was an
/// integer. The [`Float`] is taken by reference.
///
/// The rounding mode gives the integer-rounding direction: `Floor` and `Ceiling` are the floor
/// and ceiling functions, `Down` is truncation, `Up` rounds away from zero, and `Nearest`
/// rounds to the nearest integer with ties to even. `Exact` is not allowed.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Panics if `rm` is `Exact`.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_round_ref(Ceiling),
/// (Float::from(3u32), Greater, false)
/// );
/// assert_eq!(
/// x.round_to_integer_round_ref(Floor),
/// (Float::TWO, Less, false)
/// );
/// ```
#[inline]
pub fn round_to_integer_round_ref(&self, rm: RoundingMode) -> (Self, Ordering, bool) {
self.round_to_integer_helper(self.significant_bits(), rm, false)
}
/// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
/// ties going to even. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by value.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Never panics.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_float::Float;
///
/// // ties to even
/// let x = Float::from(2.5f64);
/// assert_eq!(x.round_to_integer_ref(), (Float::TWO, Less, false));
/// ```
#[inline]
pub fn round_to_integer(self) -> (Self, Ordering, bool) {
self.round_to_integer_helper(self.significant_bits(), Nearest, false)
}
/// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
/// ties going to even. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by reference.
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Never panics.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::num::basic::traits::Two;
/// use malachite_float::Float;
///
/// // ties to even
/// let x = Float::from(2.5f64);
/// assert_eq!(x.round_to_integer_ref(), (Float::TWO, Less, false));
/// ```
#[inline]
pub fn round_to_integer_ref(&self) -> (Self, Ordering, bool) {
self.round_to_integer_helper(self.significant_bits(), Nearest, false)
}
/// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
/// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by value.
///
/// The result is produced by a single rounding to an integer representable at the target
/// precision: if the input's integer part needs more bits than the precision provides, no
/// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
/// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. Ties round away
/// from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the other
/// integer-rounding directions are available through [`Float::round_to_integer_prec_round`].
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_float::Float;
///
/// // ties away from zero
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_ties_away_prec_ref(4),
/// (Float::from(3u32), Greater, false)
/// );
/// ```
#[inline]
pub fn round_to_integer_ties_away_prec(self, prec: u64) -> (Self, Ordering, bool) {
self.round_to_integer_helper(prec, Nearest, true)
}
/// Rounds a [`Float`] to the nearest integer representable at the specified precision, with
/// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by reference.
///
/// The result is produced by a single rounding to an integer representable at the target
/// precision: if the input's integer part needs more bits than the precision provides, no
/// intermediate integer is formed. For example, $10.5$ rounded to the nearest integer at a
/// precision of 2 bits is $12$: not first $10$, and then $10$ rounded again. Ties round away
/// from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the other
/// integer-rounding directions are available through [`Float::round_to_integer_prec_round`].
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_float::Float;
///
/// // ties away from zero
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_ties_away_prec_ref(4),
/// (Float::from(3u32), Greater, false)
/// );
/// ```
#[inline]
pub fn round_to_integer_ties_away_prec_ref(&self, prec: u64) -> (Self, Ordering, bool) {
self.round_to_integer_helper(prec, Nearest, true)
}
/// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
/// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by value.
///
/// Ties round away from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the
/// other integer-rounding directions are available through
/// [`Float::round_to_integer_prec_round`].
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Never panics.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_float::Float;
///
/// // ties away from zero
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_ties_away_ref(),
/// (Float::from(3u32), Greater, false)
/// );
/// ```
#[inline]
pub fn round_to_integer_ties_away(self) -> (Self, Ordering, bool) {
self.round_to_integer_helper(self.significant_bits(), Nearest, true)
}
/// Rounds a [`Float`] to the nearest integer representable at the input's own precision, with
/// ties going away from zero. An [`Ordering`] comparing the result to the exact input is also
/// returned, along with a `bool` indicating whether the input was an integer. The [`Float`] is
/// taken by reference.
///
/// Ties round away from zero, as in IEEE 754's roundTiesToAway and MPFR's `mpfr_round`; the
/// other integer-rounding directions are available through
/// [`Float::round_to_integer_prec_round`].
///
/// The pair of the [`Ordering`] and the `bool` carries the same information as `mpfr_rint`'s
/// ternary value: `(Equal, true)` means the input was an integer representable at the target
/// precision, returned unchanged; `(Less, true)` and `(Greater, true)` mean the input was an
/// integer that required rounding to fit the precision; `(Less, false)` and `(Greater, false)`
/// mean the input was not an integer. `(Equal, false)` cannot occur.
///
/// `NaN`s, infinities, and zeros are returned unchanged with `Equal`; of these, only zeros are
/// considered integers.
///
/// If rounding away from zero at the maximum exponent produces an integer too large to
/// represent, the result is $\pm\infty$.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `self.significant_bits()`.
///
/// # Panics
/// Never panics.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_float::Float;
///
/// // ties away from zero
/// let x = Float::from(2.5f64);
/// assert_eq!(
/// x.round_to_integer_ties_away_ref(),
/// (Float::from(3u32), Greater, false)
/// );
/// ```
#[inline]
pub fn round_to_integer_ties_away_ref(&self) -> (Self, Ordering, bool) {
self.round_to_integer_helper(self.significant_bits(), Nearest, true)
}
/// Rounds a [`Float`] to an integer in the direction `irm`, and then correctly rounds that
/// exact integer to the specified precision with `rm`. An [`Ordering`] comparing the result to
/// the exact integer is also returned. The [`Float`] is taken by value.
///
/// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
/// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
/// integer is formed first, then rounded to the target precision. The two can differ: under
/// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
/// precision of 2 bits, while the single-rounding form gives $12$.
///
/// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
/// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
/// modes rounding away from zero, and the maximum finite value at the target precision for the
/// modes rounding toward zero.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero, if `irm` is `Exact`, or if `rm` is `Exact` and the integer is not
/// exactly representable at the target precision.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(10.5f64);
/// assert_eq!(
/// x.round_to_integer_then_prec_round_ref(Nearest, 2, Nearest),
/// (Float::from(8u32), Less)
/// );
/// assert_eq!(
/// Float::from(2.5f64).round_to_integer_then_prec_round_ref(Ceiling, 10, Nearest),
/// (Float::from(3u32), Equal)
/// );
/// ```
#[inline]
pub fn round_to_integer_then_prec_round(
self,
irm: RoundingMode,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering) {
assert_ne!(irm, Exact);
self.round_to_integer_then_helper(irm, false, prec, rm)
}
/// Rounds a [`Float`] to an integer in the direction `irm`, and then correctly rounds that
/// exact integer to the specified precision with `rm`. An [`Ordering`] comparing the result to
/// the exact integer is also returned. The [`Float`] is taken by reference.
///
/// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
/// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
/// integer is formed first, then rounded to the target precision. The two can differ: under
/// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
/// precision of 2 bits, while the single-rounding form gives $12$.
///
/// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
/// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
/// modes rounding away from zero, and the maximum finite value at the target precision for the
/// modes rounding toward zero.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero, if `irm` is `Exact`, or if `rm` is `Exact` and the integer is not
/// exactly representable at the target precision.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(10.5f64);
/// assert_eq!(
/// x.round_to_integer_then_prec_round_ref(Nearest, 2, Nearest),
/// (Float::from(8u32), Less)
/// );
/// assert_eq!(
/// Float::from(2.5f64).round_to_integer_then_prec_round_ref(Ceiling, 10, Nearest),
/// (Float::from(3u32), Equal)
/// );
/// ```
#[inline]
pub fn round_to_integer_then_prec_round_ref(
&self,
irm: RoundingMode,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering) {
assert_ne!(irm, Exact);
self.round_to_integer_then_helper(irm, false, prec, rm)
}
/// Rounds a [`Float`] to the nearest integer with ties going away from zero, and then correctly
/// rounds that exact integer to the specified precision with `rm`. An [`Ordering`] comparing
/// the result to the exact integer is also returned. The [`Float`] is taken by value.
///
/// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
/// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
/// integer is formed first, then rounded to the target precision. The two can differ: under
/// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
/// precision of 2 bits, while the single-rounding form gives $12$.
///
/// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
/// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
/// modes rounding away from zero, and the maximum finite value at the target precision for the
/// modes rounding toward zero.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero, or if `rm` is `Exact` and the integer is not exactly representable
/// at the target precision.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(10.5f64);
/// assert_eq!(
/// x.round_to_integer_ties_away_then_prec_round_ref(2, Nearest),
/// (Float::from(12u32), Greater)
/// );
/// ```
#[inline]
pub fn round_to_integer_ties_away_then_prec_round(
self,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering) {
self.round_to_integer_then_helper(Nearest, true, prec, rm)
}
/// Rounds a [`Float`] to the nearest integer with ties going away from zero, and then correctly
/// rounds that exact integer to the specified precision with `rm`. An [`Ordering`] comparing
/// the result to the exact integer is also returned. The [`Float`] is taken by reference.
///
/// Unlike [`Float::round_to_integer_prec_round`], which rounds once, this function is the
/// composition of two roundings, matching MPFR's `mpfr_rint_`-prefixed functions: the exact
/// integer is formed first, then rounded to the target precision. The two can differ: under
/// this function with both modes `Nearest`, $10.5$ becomes $10$, which then rounds to $8$ at a
/// precision of 2 bits, while the single-rounding form gives $12$.
///
/// `NaN`s, infinities, and non-integer-producing specials pass through the final rounding only.
/// If the integer overflows the exponent range, the result follows `rm`: $\pm\infty$ for the
/// modes rounding away from zero, and the maximum finite value at the target precision for the
/// modes rounding toward zero.
///
/// # Worst-case complexity
/// $T(n) = O(n)$
///
/// $M(n) = O(n)$
///
/// where $T$ is time, $M$ is additional memory, and $n$ is `max(prec,
/// self.significant_bits())`.
///
/// # Panics
/// Panics if `prec` is zero, or if `rm` is `Exact` and the integer is not exactly representable
/// at the target precision.
///
/// # Examples
/// ```
/// use core::cmp::Ordering::*;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::Float;
///
/// let x = Float::from(10.5f64);
/// assert_eq!(
/// x.round_to_integer_ties_away_then_prec_round_ref(2, Nearest),
/// (Float::from(12u32), Greater)
/// );
/// ```
#[inline]
pub fn round_to_integer_ties_away_then_prec_round_ref(
&self,
prec: u64,
rm: RoundingMode,
) -> (Self, Ordering) {
self.round_to_integer_then_helper(Nearest, true, prec, rm)
}
pub(crate) fn round_to_integer_helper(
&self,
prec: u64,
rm: RoundingMode,
ties_away: bool,
) -> (Self, Ordering, bool) {
assert_ne!(prec, 0);
let Self(Finite {
sign,
exponent,
significand,
..
}) = self
else {
// NaN, infinities, and zeros are returned unchanged and are exact; among them, only
// zeros are integers.
return (self.clone(), Equal, matches!(self, Self(Zero { .. })));
};
let sign = *sign;
let neg = !sign;
let exp = *exponent;
// The rounding direction in terms of magnitude: away from zero, toward zero, or (for the
// nearest modes) not yet decided.
let rnd_away = match rm {
Floor => Some(neg),
Ceiling => Some(sign),
Down => Some(false),
Up => Some(true),
Nearest => None,
Exact => panic!("round_to_integer with the Exact rounding mode"),
};
if exp <= 0 {
// 0 < |u| < 1, so the result is 0 or +/-1, and the input is never an integer. In the
// Nearest mode, 1/2 rounds to 0 by the even rule, but to +/-1 when ties go away from
// zero.
let away = match rnd_away {
Some(away) => away,
None => exp == 0 && (ties_away || !significand.is_power_of_2()),
};
return if away {
(
signed_one(sign, prec),
if sign { Greater } else { Less },
false,
)
} else {
(
Self(Zero { sign }),
if sign { Less } else { Greater },
false,
)
};
}
// Now exp > 0, so |u| >= 1.
let (rp, exp_increment, uflags, rnd_away) =
with_float_significand_limbs(significand, |up| {
limbs_float_round_to_integer(up, u64::exact_from(exp), prec, rnd_away, ties_away)
});
if uflags == 0 {
return (
Self(Finite {
sign,
exponent: exp,
precision: prec,
significand: Natural::from_owned_limbs_asc(rp),
}),
Equal,
true,
);
}
if exp_increment && exp == Self::MAX_EXPONENT {
// The rounded integer would exceed the maximum exponent; since the rounding was away
// from zero, the result overflows to infinity.
return (
Self(Infinity { sign }),
if sign { Greater } else { Less },
uflags == 1,
);
}
let o = if rnd_away == sign { Greater } else { Less };
(
Self(Finite {
sign,
exponent: if exp_increment { exp + 1 } else { exp },
precision: prec,
significand: Natural::from_owned_limbs_asc(rp),
}),
o,
uflags == 1,
)
}
}
/// Rounds a primitive float to an integer using the given rounding mode, using emulated [`Float`]
/// arithmetic.
///
/// The result is always exactly representable. With `Floor`, `Ceiling`, `Down`, `Up`, and `Nearest`
/// this matches the standard library's `floor`, `ceil`, `trunc` (with `Down`; `Up` rounds away from
/// zero, which has no standard equivalent), and `round_ties_even`; it serves as a reference
/// implementation. NaN, infinities, and zeros are unchanged.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Panics
/// Panics if `rm` is `Exact` and the input is not an integer.
///
/// # Examples
/// ```
/// use malachite_base::num::float::NiceFloat;
/// use malachite_base::rounding_modes::RoundingMode::*;
/// use malachite_float::float::arithmetic::round_to_integer::primitive_float_round_to_integer;
///
/// assert_eq!(
/// NiceFloat(primitive_float_round_to_integer(2.5, Floor)),
/// NiceFloat(2.0)
/// );
/// assert_eq!(
/// NiceFloat(primitive_float_round_to_integer(2.5, Nearest)),
/// NiceFloat(2.0)
/// );
/// ```
#[allow(clippy::type_repetition_in_bounds)]
#[inline]
pub fn primitive_float_round_to_integer<T: PrimitiveFloat>(x: T, rm: RoundingMode) -> T
where
Float: From<T> + PartialOrd<T>,
for<'a> T: ExactFrom<&'a Float>,
{
emulate_float_to_float_fn(
|x, prec| {
let (r, o, _) = x.round_to_integer_prec_round(prec, rm);
(r, o)
},
x,
)
}
/// Rounds a primitive float to the nearest integer, with ties away from zero, using emulated
/// [`Float`] arithmetic.
///
/// This is IEEE 754's roundTiesToAway, matching the standard library's `round`; it serves as a
/// reference implementation. NaN, infinities, and zeros are unchanged.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::num::float::NiceFloat;
/// use malachite_float::float::arithmetic::round_to_integer::*;
///
/// assert_eq!(
/// NiceFloat(primitive_float_round_to_integer_ties_away(2.5)),
/// NiceFloat(3.0)
/// );
/// ```
#[allow(clippy::type_repetition_in_bounds)]
#[inline]
pub fn primitive_float_round_to_integer_ties_away<T: PrimitiveFloat>(x: T) -> T
where
Float: From<T> + PartialOrd<T>,
for<'a> T: ExactFrom<&'a Float>,
{
emulate_float_to_float_fn(
|x, prec| {
let (r, o, _) = x.round_to_integer_ties_away_prec(prec);
(r, o)
},
x,
)
}