malachite-float 0.10.0

The arbitrary-precision floating-point type Float, with efficient algorithms partially derived from MPFR.
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
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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
// Copyright © 2026 Mikhail Hogrefe
//
// Uses code adopted from the GNU MPFR Library.
//
//      Copyright 1999-2026 Free Software Foundation, Inc.
//
//      Contributed by the Pascaline and Caramba projects, INRIA.
//
// 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::InnerFloat::{Finite, Infinity, NaN, Zero};
use crate::float::basic::extended::ExtendedFloat;
use crate::{
    Float, emulate_float_to_float_fn, emulate_rational_to_float_fn, float_either_zero,
    float_infinity, float_nan, float_negative_infinity, float_zero, floor_and_ceiling,
    significand_bits,
};
use alloc::vec;
use core::cmp::Ordering::{self, *};
use core::mem::{swap, take};
use malachite_base::num::arithmetic::traits::{
    Abs, Agm, CeilingLogBase2, IsPowerOf2, Ln, LnAssign, Parity, PowerOf2, Sign,
};
use malachite_base::num::basic::floats::PrimitiveFloat;
use malachite_base::num::basic::integers::PrimitiveInt;
use malachite_base::num::basic::traits::{NegativeInfinity, One, Zero as ZeroTrait};
use malachite_base::num::conversion::traits::{ExactFrom, RoundingFrom, SaturatingFrom};
use malachite_base::num::logic::traits::SignificantBits;
use malachite_base::rounding_modes::RoundingMode::{self, *};
use malachite_nz::integer::Integer;
use malachite_nz::natural::arithmetic::float_extras::float_can_round;
use malachite_nz::platform::Limb;
use malachite_q::Rational;

// The computation of log(x) is done using the formula: if we want p bits of the result,
// ```
//                    pi
//      log(x) ~ ------------- - m log 2
//               2 AG(1,4 / s)
// ```
// where s = x 2^m > 2^(p/2).
//
// More precisely, if F(x) = int(1 / ln(1 - (1 - x ^ 2) * sin(t) ^ 2), t = 0..pi / 2), then for s >=
// 1.26 we have log(s) < F(4 / s) < log(s) * (1 + 4 / s ^ 2) from which we deduce pi / 2 / AG(1, 4 /
// s) * (1 - 4 / s ^ 2) < log(s) < pi / 2 / AG(1, 4 / s) so the relative error 4 / s ^ 2 is < 4 / 2
// ^ p i.e. 4 ulps.
//
// When `x` lies within a sliver of 1 -- `|x - 1|` within a few binades of the smallest positive
// `Float` -- returns `x - 1`, and otherwise `None`. For such `x`, `log(x) ~ x - 1` can fall below
// the smallest positive `Float`: the working subtractions in the log loops would flush to zero or
// clamp, and the rounding test could never certify a result, so the callers delegate to the
// `1_plus_x` functions, whose tiny-argument paths handle the underflow region correctly. Reaching
// the sliver requires an input precision of nearly 2^30 bits, so for every other `x` the guard
// costs only an exponent-and-precision test; the subtraction (performed only past that test) is
// exact, since `x` is within `(1/2, 2)`. Brackets of ln(1 + e) for an exact nonzero Rational e with
// |e| < 1/2, as exact Rationals, to a relative accuracy of about 2^-wprec. Uses the Mercator series
// ln(1 + e) = sum_{k>=1} (-1)^(k+1) e^k / k. For e > 0 the terms strictly alternate in sign and
// decrease in magnitude, so consecutive partial sums bracket the value; for e < 0 every term is
// negative, so a partial sum is an upper bound and the remainder after it is bounded in magnitude
// by |e|^(k+1) / ((k + 1)(1 - |e|)). Unlike the atanh form, this needs no `e / (2 + e)` division,
// which is the dominant cost when e is a sub-`MIN` sliver (a ~128-MB Rational).
pub(crate) fn ln_1_plus_rational_brackets(e: &Rational, wprec: u64) -> (Rational, Rational) {
    let negative = *e < 0u32;
    let mut pow = e.clone(); // e^k
    let mut s = e.clone(); // partial sum S_k
    let mut k = 1u64;
    loop {
        pow *= e; // e^(k+1)
        k += 1;
        let mut term = &pow / Rational::from(k); // (-1)^(k+1) e^k / k, up to sign
        if k.even() {
            term = -term;
        }
        let s_next = &s + &term; // S_{k+1}
        let (lo, hi) = if negative {
            // S_{k+1} is an upper bound; the remainder is bounded in magnitude by |e|^(k+2) / ((k +
            // 2)(1 - |e|)), and 1 - |e| = 1 + e for e < 0.
            let bound = -((&pow * e) / (Rational::from(k + 1) * (Rational::ONE + e))).abs();
            (&s_next + &bound, s_next.clone())
        } else if s < s_next {
            (s.clone(), s_next.clone())
        } else {
            (s_next.clone(), s.clone())
        };
        s = s_next;
        let width = &hi - &lo;
        if width == 0u32
            || width.floor_log_base_2_abs() < lo.floor_log_base_2_abs() - i64::exact_from(wprec) - 2
        {
            return (lo, hi);
        }
    }
}

pub(crate) enum SliverOfOne {
    // `x` is not within a sliver of 1; use the ordinary logarithm path.
    No,
    // `x = 1 + d` with `d` representable; compute the logarithm via the `1_plus_x` form.
    Representable(Float),
    // `x` is so close to 1 that its logarithm falls at or below the smallest positive `Float`. The
    // subtraction `x - 1` cannot be represented (it flushes to zero for `x > 1`, or clamps to the
    // minimum magnitude for `x < 1`), so the caller computes the underflowing result via the
    // exact-`Rational` logarithm of `x` (whose Rational-argument path has no exponent range).
    Underflow,
}

pub(crate) fn sliver_of_one(x: &Float) -> SliverOfOne {
    let e = i64::from(x.get_exponent().unwrap());
    if (e == 0 || e == 1)
        && x.get_prec().unwrap() >= u64::exact_from(-i64::from(Float::MIN_EXPONENT) - 8)
    {
        let (mut d, o) = x.sub_prec_round_ref_val(Float::ONE, x.get_prec().unwrap() + 1, Floor);
        if o != Equal {
            // `x - 1` fell below the smallest positive `Float`, so `ln(x) ~ x - 1` underflows.
            return SliverOfOne::Underflow;
        }
        if i64::from(d.get_exponent().unwrap()) <= i64::from(Float::MIN_EXPONENT) + 4 {
            // Shed the trailing zeros inherited from the subtraction's requested precision: d's
            // true significant span is small, and the inflated precision would defeat the
            // `1_plus_x` functions' round-near-x shortcut (a significand padded with ~2^30 trailing
            // zeros fails their rounding test).
            let sig = d.significand_ref().unwrap();
            let min_prec = significand_bits(sig) - sig.trailing_zeros().unwrap();
            let o = d.set_prec_round(min_prec, Floor);
            debug_assert_eq!(o, Equal);
            return SliverOfOne::Representable(d);
        }
    }
    SliverOfOne::No
}

// This is mpfr_log from log.c, MPFR 4.2.0.
fn ln_prec_round_normal_ref(x: &Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
    if *x == 1u32 {
        return (Float::ZERO, Equal);
    }
    // ln(x) for x in a sliver of 1 can fall below the smallest positive Float; the 1-plus-x form
    // handles that underflow region.
    match sliver_of_one(x) {
        SliverOfOne::Representable(d) => return d.ln_1_plus_x_prec_round(prec, rm),
        SliverOfOne::Underflow => {
            return Float::ln_rational_prec_round(Rational::exact_from(x), prec, rm);
        }
        SliverOfOne::No => {}
    }
    assert_ne!(rm, Exact, "Inexact ln");
    let x_exp = i64::from(x.get_exponent().unwrap());
    // use initial precision about q + 2 * lg(q) + cte
    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
    let mut increment = Limb::WIDTH;
    let mut previous_m = 0;
    let mut x = x.clone();
    loop {
        // Calculus of m (depends on p)
        let m = i64::exact_from((working_prec + 3) >> 1)
            .checked_sub(x_exp)
            .unwrap();
        x <<= m - previous_m;
        previous_m = m;
        assert!(x.is_normal());
        let tmp2 = Float::pi_prec(working_prec).0
            / (Float::ONE.agm(
                const { Float::const_from_unsigned(4) }
                    .div_prec_round_val_ref(&x, working_prec, Floor)
                    .0,
            ) << 1u32);
        let exp2 = tmp2.get_exponent();
        let tmp1 = tmp2
            - Float::ln_2_prec(working_prec)
                .0
                .mul_prec(Float::from(m), working_prec)
                .0;
        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
            let cancel = u64::saturating_from(exp2 - exp1);
            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
            // order term, plus the canceled bits
            if float_can_round(
                tmp1.significand_ref().unwrap(),
                working_prec.saturating_sub(cancel).saturating_sub(4),
                prec,
                rm,
            ) {
                return Float::from_float_prec_round(tmp1, prec, rm);
            }
            working_prec += cancel + working_prec.ceiling_log_base_2();
        } else {
            working_prec += working_prec.ceiling_log_base_2();
        }
        working_prec += increment;
        increment = working_prec >> 1;
    }
}

// This is mpfr_log from log.c, MPFR 4.2.0.
fn ln_prec_round_normal(mut x: Float, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
    if x == 1u32 {
        return (Float::ZERO, Equal);
    }
    // ln(x) for x in a sliver of 1 can fall below the smallest positive Float; the 1-plus-x form
    // handles that underflow region.
    match sliver_of_one(&x) {
        SliverOfOne::Representable(d) => return d.ln_1_plus_x_prec_round(prec, rm),
        SliverOfOne::Underflow => {
            return Float::ln_rational_prec_round(Rational::exact_from(&x), prec, rm);
        }
        SliverOfOne::No => {}
    }
    assert_ne!(rm, Exact, "Inexact ln");
    let x_exp = i64::from(x.get_exponent().unwrap());
    // use initial precision about q + 2 * lg(q) + cte
    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
    let mut increment = Limb::WIDTH;
    let mut previous_m = 0;
    loop {
        // Calculus of m (depends on p)
        let m = i64::exact_from((working_prec + 3) >> 1)
            .checked_sub(x_exp)
            .unwrap();
        x <<= m - previous_m;
        previous_m = m;
        assert!(x.is_normal());
        let tmp2 = Float::pi_prec(working_prec).0
            / (Float::ONE.agm(
                const { Float::const_from_unsigned(4) }
                    .div_prec_round_val_ref(&x, working_prec, Floor)
                    .0,
            ) << 1u32);
        let exp2 = tmp2.get_exponent();
        let tmp1 = tmp2
            - Float::ln_2_prec(working_prec)
                .0
                .mul_prec(Float::from(m), working_prec)
                .0;
        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
            let cancel = u64::saturating_from(exp2 - exp1);
            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
            // order term, plus the canceled bits
            if float_can_round(
                tmp1.significand_ref().unwrap(),
                working_prec.saturating_sub(cancel).saturating_sub(4),
                prec,
                rm,
            ) {
                return Float::from_float_prec_round(tmp1, prec, rm);
            }
            working_prec += cancel + working_prec.ceiling_log_base_2();
        } else {
            working_prec += working_prec.ceiling_log_base_2();
        }
        working_prec += increment;
        increment = working_prec >> 1;
    }
}

pub(crate) fn ln_prec_round_normal_extended(
    x: ExtendedFloat,
    prec: u64,
    rm: RoundingMode,
) -> (Float, Ordering) {
    if x.exp == 1 && x.x.is_power_of_2() {
        return (Float::ZERO, Equal);
    }
    assert_ne!(rm, Exact, "Inexact ln");
    let x_exp = x.exp;
    // use initial precision about q + 2 * lg(q) + cte
    let mut working_prec = prec + (prec.ceiling_log_base_2() << 1) + 10;
    let mut increment = Limb::WIDTH;
    let mut m = i64::exact_from((working_prec + 3) >> 1)
        .checked_sub(x.exp)
        .unwrap();
    let mut previous_m = m;
    let mut x = Float::exact_from(x << m);
    let mut first = true;
    loop {
        if first {
            first = false;
        } else {
            // Calculus of m (depends on p)
            m = i64::exact_from((working_prec + 3) >> 1)
                .checked_sub(x_exp)
                .unwrap();
            x <<= m - previous_m;
            previous_m = m;
        }
        assert!(x.is_normal());
        let tmp2 = Float::pi_prec(working_prec).0
            / (Float::ONE.agm(
                const { Float::const_from_unsigned(4) }
                    .div_prec_round_val_ref(&x, working_prec, Floor)
                    .0,
            ) << 1u32);
        let exp2 = tmp2.get_exponent();
        let tmp1 = tmp2
            - Float::ln_2_prec(working_prec)
                .0
                .mul_prec(Float::from(m), working_prec)
                .0;
        if let (Some(exp1), Some(exp2)) = (tmp1.get_exponent(), exp2) {
            let cancel = u64::saturating_from(exp2 - exp1);
            // we have 7 ulps of error from the above roundings, 4 ulps from the 4 / s ^ 2 second
            // order term, plus the canceled bits
            if float_can_round(
                tmp1.significand_ref().unwrap(),
                working_prec.saturating_sub(cancel).saturating_sub(4),
                prec,
                rm,
            ) {
                return Float::from_float_prec_round(tmp1, prec, rm);
            }
            working_prec += cancel + working_prec.ceiling_log_base_2();
        } else {
            working_prec += working_prec.ceiling_log_base_2();
        }
        working_prec += increment;
        increment = working_prec >> 1;
    }
}

// Computes `ln(1 + eps)` for a nonzero `Rational` `eps` of tiny magnitude (the caller guards `|eps|
// < 2^(MIN_EXPONENT + 5)`), where the result can lie below the smallest positive `Float`: the
// bracketing in `ln_rational_helper` could never resolve such a value (its `Float` approximations
// of `1 + eps` collapse to 1). The Taylor series `ln(1 + eps) = eps - eps^2/2 + eps^3/3 - ...` is
// summed term by term in exact `Rational`s, bracketing the exact value between two rationals
// (consecutive partial sums for `eps > 0`, a partial sum and a remainder bound for `eps < 0`) until
// both ends round to the same `Float`; `from_rational_prec_round` performs the final, possibly
// underflowing, clamp. Termination: `ln(1 + eps)` is irrational, so some finite bracket eventually
// separates it from every representable point and tie. This mirrors `exp_rational_near_one`.
fn ln_rational_near_one(eps: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
    let negative = *eps < 0u32;
    let mut pow = eps.clone(); // eps^k
    let mut s = eps.clone(); // S_1
    let mut k = 1u64;
    loop {
        pow *= eps;
        k += 1;
        let mut term = &pow / Rational::from(k); // |term| when k even, term when k odd
        if k.even() {
            term = -term;
        }
        let s_next = &s + &term; // S_k
        let (lo, hi) = if negative {
            // Every term is negative, so the partial sums decrease toward ln(1 + eps), and the
            // remainder after S_k is bounded in magnitude by |eps|^(k+1) / ((k + 1) (1 - |eps|)).
            let bound = (&pow * eps) / (Rational::from(k + 1) * (Rational::ONE + eps.clone()));
            // pow * eps = eps^(k+1) is negative here (odd power of a negative number) when k is
            // even... its sign alternates; take the magnitude explicitly.
            let bound = -bound.abs();
            (&s_next + bound, s_next.clone())
        } else {
            // The terms alternate in sign with strictly decreasing magnitude, so ln(1 + eps) lies
            // between consecutive partial sums.
            if s < s_next {
                (s.clone(), s_next.clone())
            } else {
                (s_next.clone(), s.clone())
            }
        };
        s = s_next;
        let (f_lo, mut o_lo) = Float::from_rational_prec_round_ref(&lo, prec, rm);
        let (f_hi, mut o_hi) = Float::from_rational_prec_round_ref(&hi, prec, rm);
        // A bound that is exactly representable rounds with `Equal`; the exact value lies strictly
        // inside the bracket, so treat it as agreeing with the other bound.
        if o_lo == Equal {
            o_lo = o_hi;
        }
        if o_hi == Equal {
            o_hi = o_lo;
        }
        if o_lo == o_hi && f_lo == f_hi {
            return (f_lo, o_lo);
        }
    }
}

fn ln_rational_helper(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
    let mut working_prec = prec + 10;
    let mut increment = Limb::WIDTH;
    loop {
        let (x_lo, x_o) = Float::from_rational_prec_round_ref(x, working_prec, Floor);
        if x_o == Equal {
            return ln_prec_round_normal(x_lo, prec, rm);
        }
        let (x_lo, x_hi) = floor_and_ceiling((x_lo, x_o));
        let (ln_lo, mut o_lo) = ln_prec_round_normal(x_lo, prec, rm);
        let (ln_hi, mut o_hi) = ln_prec_round_normal(x_hi, prec, rm);
        if o_lo == Equal {
            o_lo = o_hi;
        }
        if o_hi == Equal {
            o_hi = o_lo;
        }
        if o_lo == o_hi && ln_lo == ln_hi {
            return (ln_lo, o_lo);
        }
        working_prec += increment;
        increment = working_prec >> 1;
    }
}

fn ln_rational_helper_extended(x: &Rational, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
    let mut working_prec = prec + 10;
    let mut increment = Limb::WIDTH;
    loop {
        let (x_lo, x_o) = ExtendedFloat::from_rational_prec_round_ref(x, working_prec, Floor);
        if x_o == Equal {
            return ln_prec_round_normal_extended(x_lo, prec, rm);
        }
        let (x_lo, x_hi) = crate::float::basic::extended::floor_and_ceiling((x_lo, x_o));
        let (ln_lo, mut o_lo) = ln_prec_round_normal_extended(x_lo, prec, rm);
        let (ln_hi, mut o_hi) = ln_prec_round_normal_extended(x_hi, prec, rm);
        if o_lo == Equal {
            o_lo = o_hi;
        }
        if o_hi == Equal {
            o_hi = o_lo;
        }
        if o_lo == o_hi && ln_lo == ln_hi {
            return (ln_lo, o_lo);
        }
        working_prec += increment;
        increment = working_prec >> 1;
    }
}

// This is the recursive function S from log_ui.c, MPFR 4.2.2. It performs the binary splitting of
// the Taylor series of log(1 + x) for x = p/2^k, over the terms n1..n2: the sum is T[0]/(B[0] *
// 2^q). `p`, `b`, and `t` are per-recursion-depth scratch stacks (indexed by depth); `p_val` is odd
// or zero.
#[allow(clippy::too_many_arguments)]
fn log_ui_s(
    p: &mut [Integer],
    b: &mut [Integer],
    t: &mut [Integer],
    q: &mut u64,
    n1: u64,
    n2: u64,
    p_val: i64,
    k: u64,
    need_p: bool,
) {
    if n2 == n1 + 1 {
        p[0] = Integer::from(if n1 == 1 { p_val } else { -p_val });
        *q = k;
        b[0] = Integer::from(n1);
        // T = B * Q * S where S = P / (B * Q), thus T = P
        t[0] = p[0].clone();
    } else {
        // m = floor((n1 + n2) / 2)
        let m = (n1 >> 1) + (n2 >> 1) + (n1 & n2 & 1);
        log_ui_s(p, b, t, q, n1, m, p_val, k, true);
        let mut q1 = 0;
        let (p_head, p_tail) = p.split_first_mut().unwrap();
        let (b_head, b_tail) = b.split_first_mut().unwrap();
        let (t_head, t_tail) = t.split_first_mut().unwrap();
        log_ui_s(p_tail, b_tail, t_tail, &mut q1, m, n2, p_val, k, need_p);
        // T[0] <- T[0] * B[1] * 2^q1 + P[0] * B[0] * T[1]
        t_tail[0] *= &*p_head * &*b_head;
        *t_head = ((&*t_head * &b_tail[0]) << q1) + &t_tail[0];
        if need_p {
            *p_head *= &p_tail[0];
        }
        *q += q1;
        *b_head *= &b_tail[0];
    }
}

// This is mpfr_log_ui from log_ui.c, MPFR 4.2.2, for n >= 3.
fn ln_unsigned_prec_round_normal(n: u64, prec: u64, rm: RoundingMode) -> (Float, Ordering) {
    assert_ne!(rm, Exact, "Inexact ln");
    // Argument reduction: compute k such that 2/3 < n/2^k < 4/3, i.e., 2^(k+1) < 3n < 2^(k+2). So k
    // = sizeinbase(3n, 2) - 2.
    let three_n = 3u128 * u128::from(n);
    let k = u64::from(128 - three_n.leading_zeros() - 2);
    // The reduced argument is (n - 2^k)/2^k. p = n - 2^k satisfies |p| < 2^k/3 < n/2 <= i64::MAX,
    // so it fits in an i64.
    let mut p = i64::exact_from(i128::from(n) - i128::power_of_2(k));
    let mut kk = k;
    if p != 0 {
        // replace p/2^kk by (p/2)/2^(kk-1) so that p is odd
        let zeros = p.trailing_zeros();
        p >>= zeros;
        kk -= u64::from(zeros);
    }
    let mut w = prec + prec.ceiling_log_base_2() + 10;
    loop {
        // We need at most w/log2(2^kk/|p|) = w/(kk - log2|p|) terms for an accuracy of w bits.
        let abs_p = p.unsigned_abs();
        let n_terms = if abs_p == 0 {
            2
        } else {
            let log2_abs_p = if abs_p == 1 {
                0
            } else {
                abs_p.ceiling_log_base_2()
            };
            w.div_ceil(kk - log2_abs_p).max(2)
        };
        // The binary-splitting integers T[0] and B[0] * 2^q0 have about n_terms * (log2(n_terms) +
        // kk) bits; if that exceeds the Float exponent range, converting them to Floats would
        // overflow to Infinity. In that extreme-precision regime, fall back to the
        // arithmetic-geometric-mean logarithm, which is correct at any precision and produces the
        // same correctly-rounded result.
        let integer_bits = n_terms.saturating_mul(n_terms.ceiling_log_base_2().saturating_add(kk));
        if integer_bits.saturating_add(64) >= Float::MAX_EXPONENT_U64 {
            return Float::from(n).ln_prec_round(prec, rm);
        }
        let lg_n = usize::exact_from(n_terms.ceiling_log_base_2() + 1);
        let mut scratch = vec![Integer::ZERO; lg_n * 3];
        split_into_chunks_mut!(scratch, lg_n, [p_arr, b_arr], t_arr);
        let mut q0 = 0;
        log_ui_s(p_arr, b_arr, t_arr, &mut q0, 1, n_terms, p, kk, false);
        // t = T[0] / (B[0] * 2^q0) = log(n/2^k) approximately
        let t_num = Float::from_integer_prec(take(&mut t_arr[0]), w).0;
        let t_den = Float::from_integer_prec(take(&mut b_arr[0]), w).0 << q0;
        // argument reconstruction: add k * log(2)
        let t = t_num / t_den + Float::ln_2_prec(w).0 * Float::from_unsigned_prec(k, w).0;
        // The maximal error is at most k + 6 ulps.
        let err = (k + 6).ceiling_log_base_2() + 1;
        if float_can_round(
            t.significand_ref().unwrap(),
            w.saturating_sub(err),
            prec,
            rm,
        ) {
            return Float::from_float_prec_round(t, prec, rm);
        }
        w += w >> 1;
    }
}

impl Float {
    /// Computes the natural logarithm of a [`Float`], rounding the result to the specified
    /// precision and with the specified rounding mode. The [`Float`] is taken by value. An
    /// [`Ordering`] is also returned, indicating whether the rounded logarithm is less than, equal
    /// to, or greater than the exact logarithm. Although `NaN`s are not comparable to any
    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// f(x,p,m) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(\text{NaN},p,m)=\text{NaN}$
    /// - $f(\infty,p,m)=\infty$
    /// - $f(-\infty,p,m)=\text{NaN}$
    /// - $f(\pm0.0,p,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec`] instead. If you
    /// know that your target precision is the precision of the input, consider using
    /// [`Float::ln_round`] instead. If both of these things are true, consider using [`Float::ln`]
    /// instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round(5, Floor);
    /// assert_eq!(ln.to_string(), "2.25");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round(5, Ceiling);
    /// assert_eq!(ln.to_string(), "2.38");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round(5, Nearest);
    /// assert_eq!(ln.to_string(), "2.25");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round(20, Floor);
    /// assert_eq!(ln.to_string(), "2.3025818");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round(20, Ceiling);
    /// assert_eq!(ln.to_string(), "2.3025856");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round(20, Nearest);
    /// assert_eq!(ln.to_string(), "2.3025856");
    /// assert_eq!(o, Greater);
    /// ```
    #[inline]
    pub fn ln_prec_round(self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
        assert_ne!(prec, 0);
        match self {
            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
                (float_nan!(), Equal)
            }
            float_either_zero!() => (float_negative_infinity!(), Equal),
            float_infinity!() => (float_infinity!(), Equal),
            _ => ln_prec_round_normal(self, prec, rm),
        }
    }

    /// Computes the natural logarithm of a [`Float`], rounding the result to the specified
    /// precision and with the specified rounding mode. The [`Float`] is taken by reference. An
    /// [`Ordering`] is also returned, indicating whether the rounded logarithm is less than, equal
    /// to, or greater than the exact logarithm. Although `NaN`s are not comparable to any
    /// [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// f(x,p,m) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(\text{NaN},p,m)=\text{NaN}$
    /// - $f(\infty,p,m)=\infty$
    /// - $f(-\infty,p,m)=\text{NaN}$
    /// - $f(\pm0.0,p,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec_ref`] instead. If you
    /// know that your target precision is the precision of the input, consider using
    /// [`Float::ln_round_ref`] instead. If both of these things are true, consider using
    /// `(&Float).ln()`instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round_ref(5, Floor);
    /// assert_eq!(ln.to_string(), "2.25");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round_ref(5, Ceiling);
    /// assert_eq!(ln.to_string(), "2.38");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round_ref(5, Nearest);
    /// assert_eq!(ln.to_string(), "2.25");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round_ref(20, Floor);
    /// assert_eq!(ln.to_string(), "2.3025818");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round_ref(20, Ceiling);
    /// assert_eq!(ln.to_string(), "2.3025856");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_prec_round_ref(20, Nearest);
    /// assert_eq!(ln.to_string(), "2.3025856");
    /// assert_eq!(o, Greater);
    /// ```
    #[inline]
    pub fn ln_prec_round_ref(&self, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
        assert_ne!(prec, 0);
        match self {
            Self(NaN | Infinity { sign: false } | Finite { sign: false, .. }) => {
                (float_nan!(), Equal)
            }
            float_either_zero!() => (float_negative_infinity!(), Equal),
            float_infinity!() => (float_infinity!(), Equal),
            _ => ln_prec_round_normal_ref(self, prec, rm),
        }
    }

    /// Computes the natural logarithm of a [`Float`], rounding the result to the nearest value of
    /// the specified precision. The [`Float`] is taken by value. An [`Ordering`] is also returned,
    /// indicating whether the rounded logarithm is less than, equal to, or greater than the exact
    /// logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this function
    /// returns a `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
    /// description of the `Nearest` rounding mode.
    ///
    /// $$
    /// f(x,p) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   \ln{x}\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(\text{NaN},p,m)=\text{NaN}$
    /// - $f(\infty,p,m)=\infty$
    /// - $f(-\infty,p,m)=\text{NaN}$
    /// - $f(\pm0.0,p,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_prec_round`] instead. If you know that your target precision is the precision of
    /// the input, consider using [`Float::ln`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec(5);
    /// assert_eq!(ln.to_string(), "2.25");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec(20);
    /// assert_eq!(ln.to_string(), "2.3025856");
    /// assert_eq!(o, Greater);
    /// ```
    #[inline]
    pub fn ln_prec(self, prec: u64) -> (Self, Ordering) {
        self.ln_prec_round(prec, Nearest)
    }

    /// Computes the natural logarithm of a [`Float`], rounding the result to the nearest value of
    /// the specified precision. The [`Float`] is taken by reference. An [`Ordering`] is also
    /// returned, indicating whether the rounded logarithm is less than, equal to, or greater than
    /// the exact logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this
    /// function returns a `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
    /// description of the `Nearest` rounding mode.
    ///
    /// $$
    /// f(x,p) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   \ln{x}\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(\text{NaN},p)=\text{NaN}$
    /// - $f(\infty,p)=\infty$
    /// - $f(-\infty,p)=\text{NaN}$
    /// - $f(\pm0.0,p)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_prec_round_ref`] instead. If you know that your target precision is the
    /// precision of the input, consider using `(&Float).ln()` instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec_ref(5);
    /// assert_eq!(ln.to_string(), "2.25");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_prec_ref(20);
    /// assert_eq!(ln.to_string(), "2.3025856");
    /// assert_eq!(o, Greater);
    /// ```
    #[inline]
    pub fn ln_prec_ref(&self, prec: u64) -> (Self, Ordering) {
        self.ln_prec_round_ref(prec, Nearest)
    }

    /// Computes the natural logarithm of a [`Float`], rounding the result with the specified
    /// rounding mode. The [`Float`] is taken by value. An [`Ordering`] is also returned, indicating
    /// whether the rounded logarithm is less than, equal to, or greater than the exact logarithm.
    /// Although `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN`
    /// it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
    /// description of the possible rounding modes.
    ///
    /// $$
    /// f(x,m) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the precision of the input.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the precision of the input.
    ///
    /// If the output has a precision, it is the precision of the input.
    ///
    /// Special cases:
    /// - $f(\text{NaN},m)=\text{NaN}$
    /// - $f(\infty,m)=\infty$
    /// - $f(-\infty,m)=\text{NaN}$
    /// - $f(\pm0.0,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to specify an output precision, consider using [`Float::ln_prec_round`] instead.
    /// If you know you'll be using the `Nearest` rounding mode, consider using [`Float::ln`]
    /// instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Floor);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Ceiling);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546870");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round(Nearest);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
    /// assert_eq!(o, Less);
    /// ```
    #[inline]
    pub fn ln_round(self, rm: RoundingMode) -> (Self, Ordering) {
        let prec = self.significant_bits();
        self.ln_prec_round(prec, rm)
    }

    /// Computes the natural logarithm of a [`Float`], rounding the result with the specified
    /// rounding mode. The [`Float`] is taken by reference. An [`Ordering`] is also returned,
    /// indicating whether the rounded logarithm is less than, equal to, or greater than the exact
    /// logarithm. Although `NaN`s are not comparable to any [`Float`], whenever this function
    /// returns a `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
    /// description of the possible rounding modes.
    ///
    /// $$
    /// f(x,m) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the precision of the input.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the precision of the input.
    ///
    /// If the output has a precision, it is the precision of the input.
    ///
    /// Special cases:
    /// - $f(\text{NaN},m)=\text{NaN}$
    /// - $f(\infty,m)=\infty$
    /// - $f(-\infty,m)=\text{NaN}$
    /// - $f(\pm0.0,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to specify an output precision, consider using [`Float::ln_prec_round_ref`]
    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
    /// `(&Float).ln()` instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100).0.ln_round_ref(Floor);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_round_ref(Ceiling);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546870");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::from_unsigned_prec(10u32, 100)
    ///     .0
    ///     .ln_round_ref(Nearest);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
    /// assert_eq!(o, Less);
    /// ```
    #[inline]
    pub fn ln_round_ref(&self, rm: RoundingMode) -> (Self, Ordering) {
        let prec = self.significant_bits();
        self.ln_prec_round_ref(prec, rm)
    }

    /// Computes the natural logarithm of a [`Float`] in place, rounding the result to the specified
    /// precision and with the specified rounding mode. An [`Ordering`] is returned, indicating
    /// whether the rounded logarithm is less than, equal to, or greater than the exact logarithm.
    /// Although `NaN`s are not comparable to any [`Float`], whenever this function sets the
    /// [`Float`] to `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// x \gets \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 |xy|\rfloor-p+1}$.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// See the [`Float::ln_prec_round`] documentation for information on special cases, overflow,
    /// and underflow.
    ///
    /// If you know you'll be using `Nearest`, consider using [`Float::ln_prec_assign`] instead. If
    /// you know that your target precision is the precision of the input, consider using
    /// [`Float::ln_round_assign`] instead. If both of these things are true, consider using
    /// [`Float::ln_assign`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_round_assign(5, Floor), Less);
    /// assert_eq!(x.to_string(), "2.25");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_round_assign(5, Ceiling), Greater);
    /// assert_eq!(x.to_string(), "2.38");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_round_assign(5, Nearest), Less);
    /// assert_eq!(x.to_string(), "2.25");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_round_assign(20, Floor), Less);
    /// assert_eq!(x.to_string(), "2.3025818");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_round_assign(20, Ceiling), Greater);
    /// assert_eq!(x.to_string(), "2.3025856");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_round_assign(20, Nearest), Greater);
    /// assert_eq!(x.to_string(), "2.3025856");
    /// ```
    #[inline]
    pub fn ln_prec_round_assign(&mut self, prec: u64, rm: RoundingMode) -> Ordering {
        let mut x = Self::ZERO;
        swap(self, &mut x);
        let o;
        (*self, o) = x.ln_prec_round(prec, rm);
        o
    }

    /// Computes the natural logarithm of a [`Float`] in place, rounding the result to the nearest
    /// value of the specified precision. An [`Ordering`] is returned, indicating whether the
    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
    /// `NaN`s are not comparable to any [`Float`], whenever this function sets the [`Float`] to
    /// `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
    /// description of the `Nearest` rounding mode.
    ///
    /// $$
    /// x \gets \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   \ln{x}\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// See the [`Float::ln_prec`] documentation for information on special cases, overflow, and
    /// underflow.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_prec_round_assign`] instead. If you know that your target precision is the
    /// precision of the input, consider using [`Float::ln`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_assign(5), Less);
    /// assert_eq!(x.to_string(), "2.25");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_prec_assign(20), Greater);
    /// assert_eq!(x.to_string(), "2.3025856");
    /// ```
    #[inline]
    pub fn ln_prec_assign(&mut self, prec: u64) -> Ordering {
        self.ln_prec_round_assign(prec, Nearest)
    }

    /// Computes the natural logarithm of a [`Float`] in place, rounding the result with the
    /// specified rounding mode. An [`Ordering`] is returned, indicating whether the rounded
    /// logarithm is less than, equal to, or greater than the exact logarithm. Although `NaN`s are
    /// not comparable to any [`Float`], whenever this function sets the [`Float`] to `NaN` it also
    /// returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// The precision of the output is the precision of the input. See [`RoundingMode`] for a
    /// description of the possible rounding modes.
    ///
    /// $$
    /// x \gets \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p+1}$, where $p$ is the maximum precision of the inputs.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 \|ln{x}|\rfloor-p}$, where $p$ is the maximum precision of the inputs.
    ///
    /// If the output has a precision, it is the precision of the input.
    ///
    /// See the [`Float::ln_round`] documentation for information on special cases, overflow, and
    /// underflow.
    ///
    /// If you want to specify an output precision, consider using [`Float::ln_prec_round_assign`]
    /// instead. If you know you'll be using the `Nearest` rounding mode, consider using
    /// [`Float::ln_assign`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the input
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_round_assign(Floor), Less);
    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546838");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_round_assign(Ceiling), Greater);
    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546870");
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// assert_eq!(x.ln_round_assign(Nearest), Less);
    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546838");
    /// ```
    #[inline]
    pub fn ln_round_assign(&mut self, rm: RoundingMode) -> Ordering {
        let prec = self.significant_bits();
        self.ln_prec_round_assign(prec, rm)
    }

    /// Computes the natural logarithm of a [`Rational`], rounding the result to the specified
    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
    /// [`Rational`] is taken by value. An [`Ordering`] is also returned, indicating whether the
    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
    /// returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// f(x,p,m) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p+1}$.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(0.0,p,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you know you'll be using `Nearest`, consider using [`Float::ln_rational_prec`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Floor);
    /// assert_eq!(ln.to_string(), "-0.531");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Ceiling);
    /// assert_eq!(ln.to_string(), "-0.500");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 5, Nearest);
    /// assert_eq!(ln.to_string(), "-0.500");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Floor);
    /// assert_eq!(ln.to_string(), "-0.51082611");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Ceiling);
    /// assert_eq!(ln.to_string(), "-0.51082516");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::ln_rational_prec_round(Rational::from_unsigneds(3u8, 5), 20, Nearest);
    /// assert_eq!(ln.to_string(), "-0.51082516");
    /// assert_eq!(o, Greater);
    /// ```
    #[allow(clippy::needless_pass_by_value)]
    #[inline]
    pub fn ln_rational_prec_round(x: Rational, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
        Self::ln_rational_prec_round_ref(&x, prec, rm)
    }

    /// Computes the natural logarithm of a [`Rational`], rounding the result to the specified
    /// precision and with the specified rounding mode and returning the result as a [`Float`]. The
    /// [`Rational`] is taken by reference. An [`Ordering`] is also returned, indicating whether the
    /// rounded logarithm is less than, equal to, or greater than the exact logarithm. Although
    /// `NaN`s are not comparable to any [`Float`], whenever this function returns a `NaN` it also
    /// returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// f(x,p,m) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p+1}$.
    /// - If $\ln{x}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(0.0,p,m)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you know you'll be using `Nearest`, consider using [`Float::ln_rational_prec_ref`]
    /// instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `rm` is `Exact` but the result cannot be represented exactly with the given
    /// precision.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) =
    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Floor);
    /// assert_eq!(ln.to_string(), "-0.531");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) =
    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Ceiling);
    /// assert_eq!(ln.to_string(), "-0.500");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) =
    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 5, Nearest);
    /// assert_eq!(ln.to_string(), "-0.500");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) =
    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Floor);
    /// assert_eq!(ln.to_string(), "-0.51082611");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) =
    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Ceiling);
    /// assert_eq!(ln.to_string(), "-0.51082516");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) =
    ///     Float::ln_rational_prec_round_ref(&Rational::from_unsigneds(3u8, 5), 20, Nearest);
    /// assert_eq!(ln.to_string(), "-0.51082516");
    /// assert_eq!(o, Greater);
    /// ```
    pub fn ln_rational_prec_round_ref(
        x: &Rational,
        prec: u64,
        rm: RoundingMode,
    ) -> (Self, Ordering) {
        assert_ne!(prec, 0);
        match x.sign() {
            Equal => return (float_negative_infinity!(), Equal),
            Less => return (float_nan!(), Equal),
            Greater => {}
        }
        if *x == 1u32 {
            return (float_zero!(), Equal);
        }
        assert_ne!(rm, Exact, "Inexact ln");
        // x within a sliver of 1: ln(x) ~ x - 1 may fall below the smallest positive Float, which
        // the helpers below could never resolve.
        let eps = x - Rational::ONE;
        if eps.floor_log_base_2_abs() <= i64::from(Self::MIN_EXPONENT) + 4 {
            return ln_rational_near_one(&eps, prec, rm);
        }
        let x_exp = i32::saturating_from(x.floor_log_base_2_abs()).saturating_add(1);
        if x_exp >= const { Self::MAX_EXPONENT - 1 } || x_exp <= const { Self::MIN_EXPONENT + 1 } {
            ln_rational_helper_extended(x, prec, rm)
        } else {
            ln_rational_helper(x, prec, rm)
        }
    }

    /// Computes the natural logarithm of a [`Rational`], rounding the result to the nearest value
    /// of the specified precision and returning the result as a [`Float`]. The [`Rational`] is
    /// taken by value. An [`Ordering`] is also returned, indicating whether the rounded logarithm
    /// is less than, equal to, or greater than the exact logarithm. Although `NaN`s are not
    /// comparable to any [`Float`], whenever this function returns a `NaN` it also returns `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
    /// description of the `Nearest` rounding mode.
    ///
    /// $$
    /// f(x,p) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   |\ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(0.0,p)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_rational_prec_round`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::ln_rational_prec(Rational::from_unsigneds(3u8, 5), 5);
    /// assert_eq!(ln.to_string(), "-0.500");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::ln_rational_prec(Rational::from_unsigneds(3u8, 5), 20);
    /// assert_eq!(ln.to_string(), "-0.51082516");
    /// assert_eq!(o, Greater);
    /// ```
    #[inline]
    pub fn ln_rational_prec(x: Rational, prec: u64) -> (Self, Ordering) {
        Self::ln_rational_prec_round(x, prec, Nearest)
    }

    /// Computes the natural logarithm of a [`Rational`], rounding the result to the nearest value
    /// of the specified precision and returning the result as a [`Float`]. The [`Rational`] is
    /// taken by reference. An [`Ordering`] is also returned, indicating whether the rounded
    /// logarithm is less than, equal to, or greater than the exact logarithm. Although `NaN`s are
    /// not comparable to any [`Float`], whenever this function returns a `NaN` it also returns
    /// `Equal`.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
    /// description of the `Nearest` rounding mode.
    ///
    /// $$
    /// f(x,p) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   |\ln{x}|\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(0.0,p)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_rational_prec_round_ref`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use malachite_q::Rational;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::ln_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 5);
    /// assert_eq!(ln.to_string(), "-0.500");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::ln_rational_prec_ref(&Rational::from_unsigneds(3u8, 5), 20);
    /// assert_eq!(ln.to_string(), "-0.51082516");
    /// assert_eq!(o, Greater);
    /// ```
    #[inline]
    pub fn ln_rational_prec_ref(x: &Rational, prec: u64) -> (Self, Ordering) {
        Self::ln_rational_prec_round_ref(x, prec, Nearest)
    }

    /// Computes the natural logarithm of an unsigned integer, returning a [`Float`]. The result is
    /// rounded to the specified precision and with the specified rounding mode. An [`Ordering`] is
    /// also returned, indicating whether the rounded logarithm is less than, equal to, or greater
    /// than the exact logarithm.
    ///
    /// This is typically faster than converting the integer to a [`Float`] and taking its
    /// logarithm, as it uses binary splitting of the Taylor series of the logarithm rather than the
    /// arithmetic-geometric mean iteration.
    ///
    /// See [`RoundingMode`] for a description of the possible rounding modes.
    ///
    /// $$
    /// f(n,p,m) = \ln{n}+\varepsilon.
    /// $$
    /// - If $\ln{n}$ is infinite or zero, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{n}$ is finite and nonzero, and $m$ is not `Nearest`, then $|\varepsilon| <
    ///   2^{\lfloor\log_2 (\ln{n})\rfloor-p+1}$.
    /// - If $\ln{n}$ is finite and nonzero, and $m$ is `Nearest`, then $|\varepsilon| \leq
    ///   2^{\lfloor\log_2 (\ln{n})\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(0,p,m)=-\infty$
    /// - $f(1,p,m)=0.0$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you know you'll be using `Nearest`, consider using [`Float::ln_unsigned_prec`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero, or if `rm` is `Exact` but the logarithm is irrational (that is,
    /// whenever $n \geq 2$).
    ///
    /// # Examples
    /// ```
    /// use malachite_base::rounding_modes::RoundingMode::*;
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::ln_unsigned_prec_round(10, 100, Floor);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::ln_unsigned_prec_round(10, 100, Ceiling);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546870");
    /// assert_eq!(o, Greater);
    ///
    /// let (ln, o) = Float::ln_unsigned_prec_round(1, 10, Exact);
    /// assert_eq!(ln.to_string(), "0.0");
    /// assert_eq!(o, Equal);
    /// ```
    ///
    /// This is `mpfr_log_ui` from `log_ui.c`, MPFR 4.2.2.
    pub fn ln_unsigned_prec_round(n: u64, prec: u64, rm: RoundingMode) -> (Self, Ordering) {
        assert_ne!(prec, 0);
        match n {
            // log(0) is an exact -Infinity
            0 => (Self::NEGATIVE_INFINITY, Equal),
            // log(1) = 0, the only "normal" case where the result is exact
            1 => (Self::ZERO, Equal),
            2 => Self::ln_2_prec_round(prec, rm),
            _ => ln_unsigned_prec_round_normal(n, prec, rm),
        }
    }

    /// Computes the natural logarithm of an unsigned integer, returning a [`Float`]. The result is
    /// rounded to the specified precision and to the nearest value. An [`Ordering`] is also
    /// returned, indicating whether the rounded logarithm is less than, equal to, or greater than
    /// the exact logarithm.
    ///
    /// This is typically faster than converting the integer to a [`Float`] and taking its
    /// logarithm, as it uses binary splitting of the Taylor series of the logarithm rather than the
    /// arithmetic-geometric mean iteration.
    ///
    /// If the logarithm is equidistant from two [`Float`]s with the specified precision, the
    /// [`Float`] with fewer 1s in its binary expansion is chosen. See [`RoundingMode`] for a
    /// description of the `Nearest` rounding mode.
    ///
    /// $$
    /// f(n,p) = \ln{n}+\varepsilon.
    /// $$
    /// - If $\ln{n}$ is infinite or zero, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{n}$ is finite and nonzero, then $|\varepsilon| \leq 2^{\lfloor\log_2
    ///   (\ln{n})\rfloor-p}$.
    ///
    /// If the output has a precision, it is `prec`.
    ///
    /// Special cases:
    /// - $f(0,p)=-\infty$
    /// - $f(1,p)=0.0$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to specify a rounding mode as well, consider using
    /// [`Float::ln_unsigned_prec_round`] instead.
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `prec`.
    ///
    /// # Panics
    /// Panics if `prec` is zero.
    ///
    /// # Examples
    /// ```
    /// use malachite_float::Float;
    /// use std::cmp::Ordering::*;
    ///
    /// let (ln, o) = Float::ln_unsigned_prec(10, 100);
    /// assert_eq!(ln.to_string(), "2.3025850929940456840179914546838");
    /// assert_eq!(o, Less);
    ///
    /// let (ln, o) = Float::ln_unsigned_prec(0, 10);
    /// assert_eq!(ln.to_string(), "-Infinity");
    /// assert_eq!(o, Equal);
    /// ```
    #[inline]
    pub fn ln_unsigned_prec(n: u64, prec: u64) -> (Self, Ordering) {
        Self::ln_unsigned_prec_round(n, prec, Nearest)
    }
}

impl Ln for Float {
    type Output = Self;

    /// Computes the natural logarithm of a [`Float`], taking it by value.
    ///
    /// If the output has a precision, it is the precision of the input. If the logarithm is
    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
    /// rounding mode.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// $$
    /// f(x) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
    ///
    /// Special cases:
    /// - $f(\text{NaN})=\text{NaN}$
    /// - $f(\infty)=\infty$
    /// - $f(-\infty)=\text{NaN}$
    /// - $f(\pm0.0)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using [`Float::ln_prec`]
    /// instead. If you want to specify the output precision, consider using [`Float::ln_round`]. If
    /// you want both of these things, consider using [`Float::ln_prec_round`].
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::Ln;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
    /// use malachite_float::Float;
    ///
    /// assert!(Float::NAN.ln().is_nan());
    /// assert_eq!(Float::INFINITY.ln(), Float::INFINITY);
    /// assert!(Float::NEGATIVE_INFINITY.ln().is_nan());
    /// assert_eq!(
    ///     Float::from_unsigned_prec(10u32, 100).0.ln().to_string(),
    ///     "2.3025850929940456840179914546838"
    /// );
    /// assert!(Float::from_signed_prec(-10, 100).0.ln().is_nan());
    /// ```
    #[inline]
    fn ln(self) -> Self {
        let prec = self.significant_bits();
        self.ln_prec_round(prec, Nearest).0
    }
}

impl Ln for &Float {
    type Output = Float;

    /// Computes the natural logarithm of a [`Float`], taking it by reference.
    ///
    /// If the output has a precision, it is the precision of the input. If the logarithm is
    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
    /// rounding mode.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// $$
    /// f(x) = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
    ///
    /// Special cases:
    /// - $f(\text{NaN})=\text{NaN}$
    /// - $f(\infty)=\infty$
    /// - $f(-\infty)=\text{NaN}$
    /// - $f(\pm0.0)=-\infty$
    ///
    /// Neither overflow nor underflow is possible.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_prec_ref`] instead. If you want to specify the output precision, consider using
    /// [`Float::ln_round_ref`]. If you want both of these things, consider using
    /// [`Float::ln_prec_round_ref`].
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::Ln;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
    /// use malachite_float::Float;
    ///
    /// assert!((&Float::NAN).ln().is_nan());
    /// assert_eq!((&Float::INFINITY).ln(), Float::INFINITY);
    /// assert!((&Float::NEGATIVE_INFINITY).ln().is_nan());
    /// assert_eq!(
    ///     (&Float::from_unsigned_prec(10u32, 100).0).ln().to_string(),
    ///     "2.3025850929940456840179914546838"
    /// );
    /// assert!((&Float::from_signed_prec(-10, 100).0).ln().is_nan());
    /// ```
    #[inline]
    fn ln(self) -> Float {
        let prec = self.significant_bits();
        self.ln_prec_round_ref(prec, Nearest).0
    }
}

impl LnAssign for Float {
    /// Computes the natural logarithm of a [`Float`] in place.
    ///
    /// If the output has a precision, it is the precision of the input. If the logarithm is
    /// equidistant from two [`Float`]s with the specified precision, the [`Float`] with fewer 1s in
    /// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest`
    /// rounding mode.
    ///
    /// The logarithm of any nonzero negative number is `NaN`.
    ///
    /// $$
    /// x\gets = \ln{x}+\varepsilon.
    /// $$
    /// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
    /// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2
    ///   \ln{x}\rfloor-p}$, where $p$ is the maximum precision of the inputs.
    ///
    /// See the [`Float::ln`] documentation for information on special cases, overflow, and
    /// underflow.
    ///
    /// If you want to use a rounding mode other than `Nearest`, consider using
    /// [`Float::ln_prec_assign`] instead. If you want to specify the output precision, consider
    /// using [`Float::ln_round_assign`]. If you want both of these things, consider using
    /// [`Float::ln_prec_round_assign`].
    ///
    /// # Worst-case complexity
    /// $T(n) = O(n (\log n)^2 \log\log n)$
    ///
    /// $M(n) = O(n (\log n)^2)$
    ///
    /// where $T$ is time, $M$ is additional memory, and $n$ is `self.get_prec()`.
    ///
    /// # Examples
    /// ```
    /// use malachite_base::num::arithmetic::traits::LnAssign;
    /// use malachite_base::num::basic::traits::{Infinity, NaN, NegativeInfinity};
    /// use malachite_float::Float;
    ///
    /// let mut x = Float::NAN;
    /// x.ln_assign();
    /// assert!(x.is_nan());
    ///
    /// let mut x = Float::INFINITY;
    /// x.ln_assign();
    /// assert_eq!(x, Float::INFINITY);
    ///
    /// let mut x = Float::NEGATIVE_INFINITY;
    /// x.ln_assign();
    /// assert!(x.is_nan());
    ///
    /// let mut x = Float::from_unsigned_prec(10u32, 100).0;
    /// x.ln_assign();
    /// assert_eq!(x.to_string(), "2.3025850929940456840179914546838");
    ///
    /// let mut x = Float::from_signed_prec(-10, 100).0;
    /// x.ln_assign();
    /// assert!(x.is_nan());
    /// ```
    #[inline]
    fn ln_assign(&mut self) {
        let prec = self.significant_bits();
        self.ln_prec_round_assign(prec, Nearest);
    }
}

/// Computes the natural logarithm of a primitive float. Using this function is more accurate than
/// using the default `log` function or the one provided by `libm`.
///
/// The reciprocal logarithm of any nonzero negative number is `NaN`.
///
/// $$
/// f(x) = \ln x+\varepsilon.
/// $$
/// - If $\ln x$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
/// - If $\ln x$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 \ln x\rfloor-p}$,
///   where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53 if `T` is a
///   [`f64`], but less if the output is subnormal).
///
/// Special cases:
/// - $f(\text{NaN})=\text{NaN}$
/// - $f(\infty)=\infty$
/// - $f(-\infty)=\text{NaN}$
/// - $f(\pm0.0)=-\infty$
///
/// Neither overflow nor underflow is possible.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::num::basic::traits::NegativeInfinity;
/// use malachite_base::num::float::NiceFloat;
/// use malachite_float::float::arithmetic::ln::primitive_float_ln;
///
/// assert!(primitive_float_ln(f32::NAN).is_nan());
/// assert_eq!(
///     NiceFloat(primitive_float_ln(f32::INFINITY)),
///     NiceFloat(f32::INFINITY)
/// );
/// assert!(primitive_float_ln(f32::NEGATIVE_INFINITY).is_nan());
/// assert_eq!(NiceFloat(primitive_float_ln(10.0f32)), NiceFloat(2.3025851));
/// assert!(primitive_float_ln(-10.0f32).is_nan());
/// ```
#[inline]
#[allow(clippy::type_repetition_in_bounds)]
pub fn primitive_float_ln<T: PrimitiveFloat>(x: T) -> T
where
    Float: From<T> + PartialOrd<T>,
    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
{
    emulate_float_to_float_fn(Float::ln_prec, x)
}

/// Computes the natural logarithm of a [`Rational`], returning a primitive float result.
///
/// If the logarithm is equidistant from two primitive floats, the primitive float with fewer 1s in
/// its binary expansion is chosen. See [`RoundingMode`] for a description of the `Nearest` rounding
/// mode.
///
/// The logarithm of any negative number is `NaN`.
///
/// $$
/// f(x) = \ln{x}+\varepsilon.
/// $$
/// - If $\ln{x}$ is infinite, zero, or `NaN`, $\varepsilon$ may be ignored or assumed to be 0.
/// - If $\ln{x}$ is finite and nonzero, then $|\varepsilon| < 2^{\lfloor\log_2 |\ln{x}|\rfloor-p}$,
///   where $p$ is precision of the output (typically 24 if `T` is a [`f32`] and 53 if `T` is a
///   [`f64`], but less if the output is subnormal).
///
/// Special cases:
/// - $f(0)=-\infty$
///
/// Neither overflow nor underflow is possible.
///
/// # Worst-case complexity
/// Constant time and additional memory.
///
/// # Examples
/// ```
/// use malachite_base::num::basic::traits::{NegativeInfinity, Zero};
/// use malachite_base::num::float::NiceFloat;
/// use malachite_float::float::arithmetic::ln::primitive_float_ln_rational;
/// use malachite_q::Rational;
///
/// assert_eq!(
///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::ZERO)),
///     NiceFloat(f64::NEGATIVE_INFINITY)
/// );
/// assert_eq!(
///     NiceFloat(primitive_float_ln_rational::<f64>(
///         &Rational::from_unsigneds(1u8, 3)
///     )),
///     NiceFloat(-1.0986122886681098)
/// );
/// assert_eq!(
///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::from(10000))),
///     NiceFloat(9.210340371976184)
/// );
/// assert_eq!(
///     NiceFloat(primitive_float_ln_rational::<f64>(&Rational::from(-10000))),
///     NiceFloat(f64::NAN)
/// );
/// ```
#[inline]
#[allow(clippy::type_repetition_in_bounds)]
pub fn primitive_float_ln_rational<T: PrimitiveFloat>(x: &Rational) -> T
where
    Float: PartialOrd<T>,
    for<'a> T: ExactFrom<&'a Float> + RoundingFrom<&'a Float>,
{
    emulate_rational_to_float_fn(Float::ln_rational_prec_ref, x)
}