symplex 0.39.0

Exact symbolic mathematics for Rust: calculus, summation, solving, linear algebra, transforms, compile-time dimensional analysis, and Rust/C code generation
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
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
//! Arbitrary-precision numerical evaluation with complex number support.
//!
//! This module implements [`evalf`], which evaluates a symbolic expression
//! to a decimal string with a specified number of significant digits,
//! using the [`astro_float`] crate for arbitrary-precision arithmetic.
//!
//! # Design
//!
//! Evaluation is performed bottom-up using an explicit post-order
//! traversal (no recursion).  Each sub-expression is evaluated to a
//! [`Complex`] (a pair of [`BigFloat`] values for the real and imaginary
//! parts) and cached, so shared sub-expressions (common in a hash-consed
//! DAG) are only evaluated once.
//!
//! The working precision is set higher than the requested output
//! precision to absorb rounding errors from intermediate computations.
//! If a sub-expression cannot be evaluated (e.g., it contains free
//! symbols), the function returns an error.
//!
//! # Sums
//!
//! A finite `Sum` or `Product` of at most 10,000 terms is evaluated term by
//! term.  An infinite `Sum` of a rational term (or `(−1)^k` times one) is
//! summed directly up to a cut-off and its tail from the Laurent expansion
//! of the term and the Hurwitz zeta function by Euler–Maclaurin, with a
//! proven remainder (`emsum`); one of another hypergeometric term by its term
//! ratio, with a rigorous bound on the tail (`hypsum`, after SymPy's
//! `hypsum`).  A divergent sum is [`SymplexError::Divergent`]; a
//! non-rational term that converges only polynomially, or a term that is
//! not hypergeometric, is refused.
//!
//! # Error bounds and branch cuts
//!
//! Every value carries an error bound on each of its parts (`accuracy`),
//! so an exactly real value is told apart from one whose imaginary part is
//! only within its error of 0; the side of a branch cut is taken from a
//! part outside its error ball, or by convention for an exact 0, and is
//! otherwise undecidable (more precision, then a refusal).  A sum or
//! product of complex-conjugate pairs is exactly real by its structure
//! (`conjugate`).
//!
//! # Definite integrals
//!
//! An unevaluated `DefiniteIntegral(body, var, lo, hi)` node is evaluated
//! by compiling `body` to an `f64` function and running the adaptive
//! Gauss–Kronrod quadrature from [`crate::calculus::definite`].  Its error
//! bound is the quadrature's own estimate plus the rounding of the `f64`
//! integrand values (see `eval_definite_integral`), so digits beyond it
//! are refused ([`SymplexError::PrecisionExhausted`]); requests for more
//! than [`QUADRATURE_MAX_DIGITS`] digits are refused up front with
//! [`SymplexError::NotImplemented`].  `Ex::eval_f64` serves such an
//! expression when [`QUADRATURE_F64_DIGITS`] digits are certified.

use num_bigint::BigInt;
use num_rational::Ratio;
use num_traits::Zero;
use rustc_hash::FxHashMap;

use astro_float::{BigFloat, Consts, Radix, RoundingMode, Sign, WORD_BIT_SIZE};
use num_complex::Complex64;

use crate::base::arena::Arena;
use crate::base::errors::SymplexError;
use crate::base::libfn::LibFn;
use crate::base::node::{ExprId, ExprNode};
use crate::base::walk;
use tracing::debug;

mod accuracy;
pub(crate) mod bernoulli;
mod bessel_debye;
mod bessel_order;
mod bessel_recur;
mod conjugate;
mod emsum;
mod exact;
mod extended;
mod factorials;
mod hypsum;
mod lambertw;
mod loggamma;
mod polylog;
mod sensitivity;

// ═══════════════════════════════════════════════════════════════════════════
// Complex type
// ═══════════════════════════════════════════════════════════════════════════

/// A complex number represented as (real_part, imaginary_part).
use crate::base::bigcomplex::Complex;

/// Largest number of decimal digits for which an expression containing a
/// `DefiniteIntegral` is evaluated (by `f64` quadrature) instead of
/// refused.  `Ex::eval_f64` requests exactly this many.
pub(crate) const QUADRATURE_MAX_DIGITS: u32 = 16;

// ═══════════════════════════════════════════════════════════════════════════
// Public entry point
// ═══════════════════════════════════════════════════════════════════════════

/// Evaluate `expr` numerically to `digits` decimal digits of precision.
///
/// Returns the decimal string representation of the result, or an error
/// if the expression contains free symbols, infinities, or NaN.
///
/// A number that is certainly not 0 but lies below the exponent range
/// (`erfc(10⁵)`, `exp(−10¹⁰)`, `2·besselk(0, 10¹⁰)`) is an
/// [`SymplexError::Unevaluable`] error that says so ([`underflow_error`]);
/// before 0.32 it was printed `0`.  Such numbers are held scaled where they
/// can be (`extended`): a sum of them of both signs is decided as any sum
/// (`exp(−10¹⁰) − exp(−2·10¹⁰)` is refused as nonzero, its logarithm is
/// `−10¹⁰`), and one that cannot be decided is refused
/// ([`undecided_error`]); before 0.34 both printed `0`.  A cancellation
/// that is zero to the precision reached at the scale of its terms is still
/// `0` (`exp(−10¹⁰)·(sin²1 + cos²1) − exp(−10¹⁰)`) — unless a term
/// certainly not 0 was lost below its error, or an exact input is not held
/// in full at that precision: then it is pursued to the precision that
/// shows what was lost, and refused beyond the configured maximum or below
/// the exponent range ([`Adaptive::Hidden`]; before 0.35 such values printed
/// `0`: `sin²1 + cos²1 − 1 + exp(−10¹⁰)`).
pub(crate) fn evalf(arena: &Arena, expr: ExprId, digits: u32) -> Result<String, SymplexError> {
    evalf_with(arena, expr, digits, ZeroSearch::Number, Underflow::Refuse)
}

/// What a decimal result does with a nonzero number below the exponent
/// range ([`Adaptive::Underflow`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum Underflow {
    /// Refuse it ([`underflow_error`]): 0 is not one of its digits.
    Refuse,
    /// Print `0`, for a caller that reads the result as an `f64`, whose
    /// correctly rounded value it is.
    Zero,
}

/// [`evalf`] with the [`ZeroSearch`] `search` for a value that is zero to
/// the working precision, and the [`Underflow`] policy `underflow`.
fn evalf_with(
    arena: &Arena,
    expr: ExprId,
    digits: u32,
    search: ZeroSearch,
    underflow: Underflow,
) -> Result<String, SymplexError> {
    // Convert decimal digits to binary precision with guard bits.
    // log2(10) ≈ 3.3219, so we use digits * 3.4 + 64 extra bits.
    let binary_prec = (digits as usize) * 34 / 10 + 64;
    // Ensure a reasonable minimum.
    let prec = binary_prec.max(128);

    debug!(
        digits = digits,
        binary_precision = prec,
        "evalf: starting numerical evaluation"
    );

    // Enforce the configured maximum precision.
    let max_prec = arena.config.max_evalf_precision as usize;
    if prec > max_prec {
        return Err(SymplexError::PrecisionExhausted {
            requested: digits,
            achieved: (max_prec * 10 / 34).saturating_sub(6) as u32,
        });
    }

    // Free symbols make the whole expression unevaluable; report the
    // offending symbol by name up front instead of surfacing an internal
    // cache miss from some parent node later.  Bound variables (a `Sum`
    // index, a `RootOf` polynomial variable, …) are not free and are
    // handled by the sub-tree evaluators below.
    let free = walk::free_symbols(arena, expr);
    if !free.is_empty() {
        let mut names: Vec<&str> = free
            .iter()
            .filter_map(|&id| match arena.node(id) {
                ExprNode::Symbol(sid) => Some(arena.symbol_name(*sid)),
                _ => None,
            })
            .collect();
        names.sort_unstable();
        if let Some(name) = names.first() {
            debug!(symbol = name, "evalf: expression has free symbols");
            return Err(SymplexError::FreeSymbol {
                name: (*name).to_owned(),
            });
        }
    }

    // Definite integrals are evaluated by `f64` quadrature; refuse rather
    // than print digits that are not there.
    if digits > QUADRATURE_MAX_DIGITS && contains_definite_integral(arena, expr) {
        return Err(SymplexError::NotImplemented(format!(
            "arbitrary-precision evaluation of a definite integral is not implemented \
             ({digits} digits requested, at most {QUADRATURE_MAX_DIGITS} available from \
             f64 Gauss–Kronrod quadrature); use eval_f64 or integrate_definite"
        )));
    }

    let rm = RoundingMode::ToEven;
    let mut cc = Consts::new().map_err(|e| {
        SymplexError::NotImplemented(format!("astro-float constants init failed: {e:?}"))
    })?;

    match evaluate_adaptive(arena, expr, digits, search, rm, &mut cc)? {
        Adaptive::Settled(result, _) => format_complex(&result, digits, prec, rm, &mut cc),
        Adaptive::Underflow(_)
        | Adaptive::Beyond(_)
        | Adaptive::Undecided
        | Adaptive::Hidden { .. }
            if underflow == Underflow::Zero =>
        {
            Ok("0".to_owned())
        }
        Adaptive::Underflow(_) | Adaptive::Beyond(_) => Err(underflow_error()),
        Adaptive::Undecided => Err(undecided_error()),
        Adaptive::Hidden { below_range: true } => Err(hidden_error()),
        Adaptive::Hidden { below_range: false } => Err(hidden_deep_error(digits)),
    }
}

/// The working precision behind `digits` decimal digits: `3.4` bits per
/// digit plus 64 guard bits, at least 128.
fn working_precision(digits: u32) -> usize {
    ((digits as usize) * 34 / 10 + 64).max(128)
}

/// Evaluate `expr` once at `prec` bits: its value and the exponent of its
/// error bound (see [`accuracy`]).  A failed node other than the root is
/// skipped: parent nodes (`Sum`, `Product`, `Piecewise`) evaluate their own
/// sub-trees with substitution.
fn evaluate_once(
    arena: &Arena,
    expr: ExprId,
    post_order: &[ExprId],
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Evaluated, SymplexError> {
    evaluate_tree_full(arena, expr, post_order, None, false, prec, rm, cc)
}

/// One evaluation of a whole expression: the value, its bound, and whether
/// some node lacked a value or a bound only for want of precision in its
/// arguments ([`precision_limited`]).
struct Evaluated {
    value: Complex,
    bound: accuracy::Bound,
    precision_limited: bool,
    /// The value is 0 with an underflow bound, and certainly not 0
    /// ([`accuracy::underflow_nonzero`]): what is known of it.
    underflowed_nonzero: Option<accuracy::Nonzero>,
    /// The value lies below the exponent range and is known scaled
    /// (`extended`): `value` is its placeholder.
    beyond: Option<extended::Scaled>,
    /// The nonzero terms some sum lost below its error bound
    /// ([`accuracy::Absorbed`]).
    absorbed: Option<accuracy::Absorbed>,
    /// The bits that hold every exact value of the expression in full
    /// ([`input_bits`]).
    exact_bits: u64,
    /// The bits that hold the second-order parts of the exact values with a
    /// small part ([`second_order_bits`]).
    second_bits: u64,
}

/// The error bounds of the evaluated nodes (see [`accuracy`]).
type ErrMap = FxHashMap<ExprId, accuracy::Bound>;

/// A bound variable preset to a value with an error bound.
type Seed = (ExprId, Complex, accuracy::Bound);

/// Evaluate `root` bottom-up over `post_order` (its post-order) at `prec`
/// bits: its value and error bound.  `seed` presets a bound variable (a
/// `Sum` index, a `RootSum` root).  Conditions (relations, `And`, …) have no
/// value and are skipped; `Piecewise` decides them from their operands.  A
/// node that fails is skipped when `strict` is false (a parent `Sum`,
/// `Piecewise`, … may not need it) and fails the evaluation when it is true.
#[allow(clippy::too_many_arguments)]
fn evaluate_tree(
    arena: &Arena,
    root: ExprId,
    post_order: &[ExprId],
    seed: Option<Seed>,
    strict: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    evaluate_tree_full(arena, root, post_order, seed, strict, prec, rm, cc)
        .map(|ev| (ev.value, ev.bound))
}

/// [`evaluate_tree`], and whether a node was [`precision_limited`].
///
/// A composite node of rationals and `i` takes its exact value
/// ([`exact`]); a node whose value overflows the exponent range, or is the
/// reciprocal of one that underflowed, fails with that reason
/// ([`exponent_range_error`]) rather than passing `±∞` up to a
/// `PrecisionExhausted` that no precision would cure.
#[allow(clippy::too_many_arguments)]
fn evaluate_tree_full(
    arena: &Arena,
    root: ExprId,
    post_order: &[ExprId],
    seed: Option<Seed>,
    strict: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Evaluated, SymplexError> {
    let mut cache: FxHashMap<ExprId, Complex> = FxHashMap::default();
    let mut errs: ErrMap = FxHashMap::default();
    let mut failed: FxHashMap<ExprId, SymplexError> = FxHashMap::default();
    let mut exact_values = exact::ExactMap::default();
    let mut limited = false;
    // The nodes that are, or depend on, a node without a value or a bound
    // for want of precision in its arguments ([`precision_limited`]).
    let mut tainted: rustc_hash::FxHashSet<ExprId> = rustc_hash::FxHashSet::default();
    let mut sigs = conjugate::Sigs::new();
    // The nodes whose value underflowed to 0 but is certainly not 0.
    let mut nonzero: FxHashMap<ExprId, accuracy::Nonzero> = FxHashMap::default();
    // The nodes known below the exponent range (`extended`).
    let mut exts = extended::ExtMap::default();
    // The nonzero terms the sums lost below their error bounds.
    let mut absorbed: Option<accuracy::Absorbed> = None;
    // The bits that hold every exact value in full (`input_bits`), and its
    // second-order part (`second_order_bits`).
    let mut exact_bits = 0u64;
    let mut second_bits = 0u64;
    if let Some((id, value, err)) = seed {
        sigs.record_leaf(id, &value, err);
        cache.insert(id, value);
        errs.insert(id, err);
    }
    for &id in post_order {
        if cache.contains_key(&id) || (id != root && is_condition(arena.node(id))) {
            continue;
        }
        let exact_z = exact::exact_value(arena, id, &exact_values);
        match (&exact_z, arena.node(id)) {
            (Some(z), _) => {
                exact_bits = exact_bits.max(input_bits(&z.re)).max(input_bits(&z.im));
                second_bits = second_bits
                    .max(second_order_bits(&z.re, arena))
                    .max(second_order_bits(&z.im, arena));
            }
            (None, ExprNode::Num(n)) => {
                let q = arena.num(*n);
                exact_bits = exact_bits.max(input_bits(q));
                second_bits = second_bits.max(second_order_bits(q, arena));
            }
            _ => {}
        }
        // Whether the value overflowed the exponent range.
        let mut overflowed = false;
        let mut evaluated =
            eval_node_with_error(arena, id, &cache, &errs, prec, rm, cc).and_then(|(value, e)| {
                match exponent_range_error(arena, id, &value, &cache, &errs) {
                    Some(err) => {
                        overflowed = true;
                        Err(err)
                    }
                    None => Ok((value, e)),
                }
            });
        // A value outside the exponent range, or a function of one, held
        // scaled (`extended`).
        let mut extended_value = false;
        if exact_z.is_none() {
            let underflowed = matches!(&evaluated, Ok((v, b))
                if accuracy::mag(v).is_none() && accuracy::is_underflow(b.joint()));
            let edge = extended::Edge {
                underflowed,
                overflowed,
            };
            if extended::wanted(arena, id, edge, &cache, &exts)
                && let Some(outcome) = extended::extend(
                    arena,
                    id,
                    edge,
                    &cache,
                    &errs,
                    &exts,
                    &exact_values,
                    prec,
                    rm,
                    cc,
                    &mut absorbed,
                )
            {
                extended_value = true;
                evaluated = match outcome {
                    extended::Outcome::InRange(v, b) => Ok((v, b)),
                    extended::Outcome::Beyond(s) => {
                        let placeholder = s.placeholder(prec);
                        exts.insert(id, extended::Ext::Beyond(s));
                        Ok(placeholder)
                    }
                    // No ordinary value: the node fails as before (with its
                    // own overflow, or the overflow of the argument it
                    // lacks), and only the nodes with a rule for it see it.
                    extended::Outcome::Above(s) => {
                        let err = match evaluated {
                            Err(e) => e,
                            Ok(_) => extended::overflow_error(&s),
                        };
                        exts.insert(id, extended::Ext::Above(s));
                        Err(err)
                    }
                    extended::Outcome::Near(p, d) => {
                        let ordinary = near_ordinary(evaluated, &p, &d, prec, rm);
                        exts.insert(id, extended::Ext::Near(p, d));
                        Ok(ordinary)
                    }
                };
            }
        }
        let evaluated = match (exact_z, evaluated) {
            (Some(z), evaluated) => {
                let refined = match evaluated {
                    Ok((value, e)) => exact::refine(&z, value, e, prec, rm),
                    Err(_) => exact::to_value(&z, prec, rm),
                };
                exact_values.insert(id, z);
                Ok(refined)
            }
            (None, evaluated) => evaluated,
        };
        let tainted_child = || {
            arena
                .node(id)
                .children()
                .iter()
                .any(|c| tainted.contains(c))
        };
        // A domain error of a function whose argument is ±∞ or 0 only
        // because an argument lacked precision (`loggamma` of `atanh(1 −
        // 2·10⁻⁵⁰)³`, infinite at 128 bits): no value yet, as in
        // `eval_node_with_error` for an inexact zero.
        let evaluated = match evaluated {
            Err(SymplexError::Unevaluable { .. }) if tainted_child() => {
                Ok((c_zero(prec), accuracy::Bound::UNKNOWN))
            }
            other => other,
        };
        match evaluated {
            Ok((mut value, mut e)) => {
                if precision_limited(arena.node(id), &value, e, &cache, &errs)
                    || (e.is_unknown() && tainted_child())
                {
                    limited = true;
                    tainted.insert(id);
                }
                // A sum or product of conjugate pairs and real terms is
                // exactly real (see `conjugate`); its computed imaginary
                // part is a rounding residue within its error of 0.
                if let ExprNode::Add(children) | ExprNode::Mul(children) = arena.node(id)
                    && !e.is_unknown()
                    && !accuracy::exact_zero(&value.1, e.im)
                    && accuracy::part_contains_zero(&value.1, e.im)
                    && sigs.conjugates_pair_up(children, &cache, &errs)
                {
                    value.1 = BigFloat::new(prec);
                    e.im = accuracy::EXACT;
                }
                sigs.record(arena, id, &value, e, &cache, &errs);
                // A sum known scaled recorded its lost terms itself
                // (`extended`); an exact one lost nothing.
                if let ExprNode::Add(children) = arena.node(id)
                    && !exact_values.contains_key(&id)
                    && !matches!(exts.get(&id), Some(extended::Ext::Beyond(_)))
                {
                    note_absorbed(
                        children,
                        e.joint(),
                        &cache,
                        &errs,
                        &exts,
                        &nonzero,
                        &mut absorbed,
                    );
                }
                if !exts.contains_key(&id) {
                    note_series_tail(arena.node(id), e.joint(), &cache, &errs, &mut absorbed);
                    note_limit_tail(
                        arena,
                        arena.node(id),
                        e.joint(),
                        &cache,
                        &errs,
                        &mut absorbed,
                    );
                    note_cross_terms(
                        arena,
                        id,
                        &value,
                        e.joint(),
                        &cache,
                        &errs,
                        &exact_values,
                        &mut absorbed,
                    );
                }
                if !extended_value && !exact_values.contains_key(&id) {
                    note_flattened(arena.node(id), e.joint(), &exts, &nonzero, &mut absorbed);
                }
                if accuracy::mag(&value).is_none() && accuracy::is_underflow(e.joint()) {
                    let status = match exts.get(&id) {
                        Some(extended::Ext::Beyond(s)) => s.nonzero(),
                        _ => accuracy::underflow_nonzero(arena, id, &cache, &errs, &nonzero),
                    };
                    if let Some(s) = status {
                        nonzero.insert(id, s);
                    }
                }
                errs.insert(id, e);
                cache.insert(id, value);
            }
            Err(e) => {
                let e = root_cause(arena.node(id), e, &failed);
                // A value above the exponent range held scaled is refused at
                // the root only: its parent may bring it back.
                let above = matches!(exts.get(&id), Some(extended::Ext::Above(_)));
                if (strict && !above) || id == root {
                    return Err(e);
                }
                failed.insert(id, e);
            }
        }
    }
    let value = cache.remove(&root).ok_or_else(|| {
        SymplexError::NotImplemented("evalf: expression not found in cache".into())
    })?;
    let err = errs.get(&root).copied().unwrap_or(accuracy::Bound::UNKNOWN);
    let beyond = match exts.remove(&root) {
        Some(extended::Ext::Beyond(s)) => Some(s),
        _ => None,
    };
    if let Some(s) = &beyond {
        extended::note_hidden(s, prec, rm, &mut absorbed);
    }
    Ok(Evaluated {
        value,
        bound: err,
        precision_limited: limited,
        underflowed_nonzero: nonzero.get(&root).copied(),
        beyond,
        absorbed,
        exact_bits,
        second_bits,
    })
}

/// The ordinary value of a node known as `p + d` (`extended::Ext::Near`,
/// `d` below the exponent range): its own when it is `p` within its bound
/// (`exp`, `cos` or a power of `1 + d` at the placeholder of `d`), otherwise
/// `p` within the underflow bound — a node without an ordinary value, or `ln`
/// of a value outside the range, `ln(e^(−10¹⁰) + e^(−2·10¹⁰)) = −10¹⁰ +
/// e^(−10¹⁰) + …`, whose ordinary value is that of `ln(0 ± underflow)`.
fn near_ordinary(
    evaluated: Result<(Complex, accuracy::Bound), SymplexError>,
    p: &exact::Gauss,
    d: &extended::Scaled,
    prec: usize,
    rm: RoundingMode,
) -> (Complex, accuracy::Bound) {
    let (pv, pb) = exact::to_value(p, prec, rm);
    if let Ok((v, b)) = evaluated
        && !b.is_unknown()
        && accuracy::mag(&v).is_some()
    {
        let diff = c_sub(&v, &pv, prec + 8, rm);
        let within = |x: &BigFloat, e: accuracy::ErrExp, f: accuracy::ErrExp| {
            accuracy::part_contains_zero(x, accuracy::shift(accuracy::lsum(e, f), 1.0))
        };
        if within(&diff.0, b.re, pb.re) && within(&diff.1, b.im, pb.im) {
            return (v, b);
        }
    }
    let u = accuracy::UNDERFLOW;
    let real = accuracy::exactly_real(&d.m, d.eb);
    let b = accuracy::Bound {
        re: accuracy::lsum(pb.re, u),
        im: if real {
            pb.im
        } else {
            accuracy::lsum(pb.im, u)
        },
    };
    (pv, b)
}

/// Record in `slot` the terms of a sum (`children`, with the error bound
/// `2^radius`) that are certainly not 0 and smaller than that bound
/// ([`accuracy::Absorbed`]): a value in range whose ball excludes 0, one
/// known below the exponent range (`extended`), or one that underflowed but
/// is certainly not 0 (its magnitude below the underflow bound).
fn note_absorbed(
    children: &[ExprId],
    radius: accuracy::ErrExp,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    exts: &extended::ExtMap,
    nonzero: &FxHashMap<ExprId, accuracy::Nonzero>,
    slot: &mut Option<accuracy::Absorbed>,
) {
    if !radius.is_finite() {
        return;
    }
    for c in children {
        let term = match exts.get(c) {
            Some(extended::Ext::Beyond(s)) => {
                if s.nonzero().is_none() {
                    continue;
                }
                s.lg_value()
            }
            _ => {
                let (Some(v), Some(b)) = (cache.get(c), errs.get(c)) else {
                    continue;
                };
                if !b.is_unknown() && !accuracy::contains_zero(v, b.joint()) {
                    accuracy::lg_abs(v)
                } else if nonzero.contains_key(c) {
                    accuracy::UNDERFLOW
                } else {
                    continue;
                }
            }
        };
        accuracy::Absorbed::note(slot, term, radius);
    }
}

/// Record in `slot` the part below the exponent range, certainly not 0, of
/// an argument of `node` that the node's ordinary value (with the error
/// bound `2^radius`) does not hold ([`accuracy::Absorbed`]): an argument
/// known scaled below the range (`extended`), the part `d` of one that is
/// `p + d`, or one that underflowed but is certainly not 0, taken by a node
/// without a rule of its own for it — its argument is the placeholder `0 ±
/// underflow` or `p ± underflow`, so its value is `f(0)` or `f(p)`.  A
/// cancellation against `f(p)` leaves the lost part: before 0.36
/// `sin(exp(e^(−10¹⁰))) − sin 1` (truly `cos 1·e^(−10¹⁰)`), `besselj(0,
/// e^(−10¹⁰)) − 1`, `erfc(e^(−10¹⁰)) − 1`, `2^(e^(−10¹⁰)) − 1` and
/// `cos(besselk(0, 10¹⁰)) − 1` printed `0` (`besselj(0, T) − 1 = −T²/4 +
/// O(T⁴)` by SymPy's series, for `T = e^(−10¹⁰)` mpmath
/// `-exp(-mpf(10)**10)**2/4` = `-2.15e-8685889639`).
fn note_flattened(
    node: &ExprNode,
    radius: accuracy::ErrExp,
    exts: &extended::ExtMap,
    nonzero: &FxHashMap<ExprId, accuracy::Nonzero>,
    slot: &mut Option<accuracy::Absorbed>,
) {
    if !radius.is_finite() {
        return;
    }
    for c in node.children().iter() {
        let term = match exts.get(c) {
            Some(extended::Ext::Beyond(s)) => {
                if s.nonzero().is_none() {
                    continue;
                }
                s.lg_value()
            }
            Some(extended::Ext::Near(_, d)) => {
                if d.nonzero().is_none() {
                    continue;
                }
                d.lg_value()
            }
            None if nonzero.contains_key(c) => accuracy::UNDERFLOW,
            // (A node with a value above the range has none of its own.)
            Some(extended::Ext::Above(_)) | None => continue,
        };
        accuracy::Absorbed::note(slot, term, radius);
    }
}

/// Record in `slot` the first term of the Taylor series at 0 of an
/// elementary function at a small argument that its value (with the error
/// bound `2^radius`) cannot show ([`accuracy::Absorbed`]): `x³/3` or `x⁵/5`
/// of `atan x`, `x²/2` or `x⁴/24` of `cos x`, `x`, `x²/2` or `x³/6` of
/// `exp x`.  The value is right within its bound, but a cancellation against
/// the leading terms leaves that term: `atan(10⁻⁴⁰⁰)·(sin²1 + cos²1) −
/// 10⁻⁴⁰⁰` is `−10⁻¹²⁰⁰/3` (before 0.35 it printed `0`), and the same
/// `+ 10⁻¹²⁰⁰/3` is `2·10⁻²⁰⁰¹` (before 0.36 it printed `0`: only the
/// first term was recorded).  Only for an argument certainly not 0 below
/// `2⁻⁸`, where the series is dominated by its first terms.
fn note_series_tail(
    node: &ExprNode,
    radius: accuracy::ErrExp,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    slot: &mut Option<accuracy::Absorbed>,
) {
    // `log₂` of the coefficients of the third and fifth powers of the odd
    // functions (the smallest of each group: a term taken smaller only sends
    // the search deeper).
    const THIRD: f64 = -1.584_962_500_721_156; // log₂(1/3)
    const SIXTH: f64 = -2.584_962_500_721_156; // log₂(1/6)
    const TWO_FIFTEENTHS: f64 = -2.906_890_595_608_519; // log₂(2/15)
    const ONE_120TH: f64 = -6.906_890_595_608_519; // log₂(1/120)
    let (c, terms): (ExprId, &[(f64, f64)]) = match *node {
        ExprNode::Sin(c) | ExprNode::Sinh(c) | ExprNode::Asin(c) | ExprNode::Asinh(c) => {
            (c, &[(SIXTH, 3.0), (ONE_120TH, 5.0)])
        }
        ExprNode::Tan(c) | ExprNode::Tanh(c) | ExprNode::Atan(c) | ExprNode::Atanh(c) => {
            (c, &[(THIRD, 3.0), (TWO_FIFTEENTHS, 5.0)])
        }
        // `2/(3√π)`, `2/(10√π)`.
        ExprNode::Erf(c) => (
            c,
            &[
                (-1.410_710_565_457_315_5, 3.0),
                (-3.147_675_390_659_634, 5.0),
            ],
        ),
        // `1/2`, `1/24`.
        ExprNode::Cos(c) | ExprNode::Cosh(c) => (c, &[(-1.0, 2.0), (-4.584_962_500_721_156, 4.0)]),
        ExprNode::Exp(c) => (c, &[(0.0, 1.0), (-1.0, 2.0), (SIXTH, 3.0)]),
        _ => return,
    };
    if !radius.is_finite() {
        return;
    }
    let (Some(x), Some(b)) = (cache.get(&c), errs.get(&c)) else {
        return;
    };
    if b.is_unknown() || accuracy::contains_zero(x, b.joint()) {
        return;
    }
    let lx = accuracy::lg_abs(x);
    if lx.is_nan() || lx >= -8.0 {
        return;
    }
    // The largest term below the bound (the series decreases).
    if let Some(t) = terms
        .iter()
        .map(|&(lc, n)| lc + n * lx)
        .find(|&t| t < radius)
    {
        accuracy::Absorbed::note(slot, t, radius);
    }
}

/// Record in `slot` the distance of a function from the value it tends to
/// — its limit at infinity, or the leading term of its asymptotic expansion
/// — when its value (with the error bound `2^radius`) cannot show it
/// ([`accuracy::Absorbed`]): `1 − tanh x ≥ e^(−2x)`, `π/2 − atan x ≥
/// 1/(2x)`, `1 − erf x = erfc(−(−x)) ≥ e^(−x²)/(2x√π)` (`x ≥ 1`), `ζ(s) − 1 ≥
/// 2^(−s)`, `1 − η(s) ≥ 2^(−s−1)` (`s ≥ 2`), `Li_s(z) − z ≥
/// abs(z)²·2^(−s−1)` (`s ≥ 4`, `0 < abs(z) ≤ 1`), `abs(asinh x − sign(x)·ln(2·abs(x)))`
/// and `abs(acosh x − ln 2x) ≥ 1/(8x²)` (`abs(x) ≥ 2`) — lower bounds, at the end
/// of the argument's ball nearer to the limit.  The value is right within
/// its bound, but a cancellation against the limit leaves that distance:
/// before 0.37 `tanh(400) − 1` (truly `−7.34·10⁻³⁴⁸`), `erf(30) − 1`,
/// `atan(10⁴⁰⁰) − π/2`, `zeta(2000) − 1` and `polylog(2000, 1/2) − 1/2`
/// printed `0` (mpmath at 30 digits does too; SymPy's `N(…, maxn=2000)` finds
/// them).
fn note_limit_tail(
    arena: &Arena,
    node: &ExprNode,
    radius: accuracy::ErrExp,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    slot: &mut Option<accuracy::Absorbed>,
) {
    if !radius.is_finite() {
        return;
    }
    // `log₂ abs(x)` of a real argument, and of the end of its ball nearer to
    // infinity (the tails fall with `abs(x)`).
    let real = |c: ExprId| -> Option<(f64, f64, bool)> {
        let (v, b) = (cache.get(&c)?, errs.get(&c)?);
        if b.is_unknown() || !accuracy::exactly_real(v, *b) || v.0.is_zero() {
            return None;
        }
        let lx = accuracy::lg_abs(v);
        let far = accuracy::lsum(lx, b.re + 1.0);
        (lx.is_finite() && far.is_finite()).then_some((lx, far, v.0.is_negative()))
    };
    let e2 = |l: f64| l.exp2();
    const LOG2_E: f64 = std::f64::consts::LOG2_E;
    let tail = || -> Option<f64> {
        Some(match *node {
            ExprNode::Tanh(c) => {
                let (lx, far, _) = real(c)?;
                (lx >= 0.0).then_some(())?;
                -2.0 * e2(far) * LOG2_E
            }
            ExprNode::Atan(c) => {
                let (lx, far, _) = real(c)?;
                (lx >= 0.0).then_some(())?;
                -1.0 - far
            }
            ExprNode::Erf(c) | ExprNode::Erfc(c) => {
                let (lx, far, negative) = real(c)?;
                (lx >= 0.0 && (negative || matches!(node, ExprNode::Erf(_)))).then_some(())?;
                // `log₂(2√π) = 1.8257…`.
                -e2(2.0 * far) * LOG2_E - 1.83 - far
            }
            ExprNode::Asinh(c) | ExprNode::Acosh(c) => {
                let (lx, far, negative) = real(c)?;
                (lx >= 1.0 && !(negative && matches!(node, ExprNode::Acosh(_)))).then_some(())?;
                -3.0 - 2.0 * far
            }
            ExprNode::Zeta(c) => {
                let (lx, far, negative) = real(c)?;
                (!negative && lx >= 1.0).then_some(())?;
                -e2(far)
            }
            ExprNode::Apply(sid, ref args) => match (arena.lib_fn(sid), args.as_slice()) {
                (Some(LibFn::DirichletEta), &[s]) => {
                    let (ls, far, negative) = real(s)?;
                    (!negative && ls >= 1.0).then_some(())?;
                    -e2(far) - 1.0
                }
                (Some(LibFn::PolyLog), &[s, z]) => {
                    let (ls, _, negative) = real(s)?;
                    (!negative && ls >= 2.0).then_some(())?;
                    polylog_tail(
                        cache.get(&s)?,
                        *errs.get(&s)?,
                        cache.get(&z)?,
                        *errs.get(&z)?,
                        radius,
                    )
                }
                _ => return None,
            },
            _ => return None,
        })
    };
    // A tail beyond `f64` lies below the exponent range.
    if let Some(t) = tail()
        && !t.is_nan()
    {
        accuracy::Absorbed::note(slot, t.max(-1e300), radius);
    }
}

/// `log₂` of a lower bound on `abs(Li_s(z) − z)` over the balls of a real `s ≥
/// 4` and of `z` (`polylog::tail_lower_bound` at their ends nearer to the
/// limit: `s` raised, `abs(z)` lowered, `abs(ln z)` raised by the ball's relative
/// radius, at most `10⁻⁶`), or a size below the exponent range — a
/// cancellation against `z` refused — where none is proved and the leading
/// term `abs(z)²·2^(−s)` is not 64 bits above the value's error `2^radius` (where
/// it is, the value shows the distance and nothing is lost).  Before 0.37 the
/// bound was for a real `abs(z) ≤ 1` only; `polylog(1270, −3) + 3` (truly
/// `9·2⁻¹²⁷⁰`) and `polylog(3598, (3 + 4i)/5) − (3 + 4i)/5`, which the faster
/// large-order expansion of 0.37 evaluates, printed `0` in development.
fn polylog_tail(
    s: &Complex,
    bs: accuracy::Bound,
    z: &Complex,
    bz: accuracy::Bound,
    radius: accuracy::ErrExp,
) -> f64 {
    let (Ok(sf), Ok(x), Ok(y)) = (
        bigfloat_to_f64_rounded(&s.0, RoundingMode::ToEven),
        bigfloat_to_f64_rounded(&z.0, RoundingMode::ToEven),
        bigfloat_to_f64_rounded(&z.1, RoundingMode::ToEven),
    ) else {
        return -1e300;
    };
    let estimate = 2.0 * x.hypot(y).log2() - sf - 1.0;
    match polylog_tail_proved(sf, s, bs, x, y, bz) {
        Some(t) => t,
        None if estimate - 64.0 >= radius => estimate - 64.0,
        None => -1e300,
    }
}

/// [`polylog_tail`]'s bound where it is proved.
fn polylog_tail_proved(
    sf: f64,
    s: &Complex,
    bs: accuracy::Bound,
    x: f64,
    y: f64,
    bz: accuracy::Bound,
) -> Option<f64> {
    const UNKNOWN_TAIL: f64 = -1e300;
    let rz = x.hypot(y);
    // Relative radii, at most 2^−20.
    let rel_s = if bs.is_exact() {
        0.0
    } else {
        bs.joint().exp2() / sf.max(1.0)
    };
    let rel_z = if bz.is_exact() {
        0.0
    } else {
        bz.joint().exp2() / rz
    };
    if rel_s.is_nan() || rel_z.is_nan() || rel_s > 1e-6 || rel_z > 1e-6 {
        return None;
    }
    let s_up = sf * (1.0 + rel_s) + rel_s;
    let s_int = s.0.is_int() && bs.is_exact();
    let near_int = {
        let d = (sf - sf.round()).abs();
        d < 1.0 / 256.0 + rel_s * sf.max(1.0)
    };
    // `abs(z)` lowered by its ball (twice); the side of the unit circle must
    // be the center's.
    let shrink = 1.0 - 2.0 * rel_z;
    let grow = 2.0 * rel_z;
    let outside = rz > 1.0;
    if (outside && rz * shrink <= 1.0) || (!outside && rz * (1.0 + grow) > 1.0) {
        return None;
    }
    let near = near_int && !s_int;
    let t = polylog::tail_lower_bound(s_up, s_int, near, x * shrink, y * shrink);
    if t <= UNKNOWN_TAIL {
        return None;
    }
    if !outside {
        return Some(t);
    }
    // `abs(ln z)` grows with the argument's change: the conditions again at the
    // far end.
    let t2 = polylog::tail_lower_bound(
        s_up,
        s_int,
        near,
        x * (1.0 + grow),
        y * (1.0 + grow) + grow * rz,
    );
    (t2 > UNKNOWN_TAIL).then_some(t)
}

/// `log₂` of the ratio of the smallest term of the sum `id` that is
/// certainly not 0 to the sum's value, when the sum is certainly not 0 —
/// or, for an exact real rational `x` that is not a sum (the canonical form
/// folds `1 + 10⁻³⁰⁰` into one rational), the size of its small part
/// ([`rational_small_part`]).
fn small_part(
    arena: &Arena,
    id: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    exact: &exact::ExactMap,
) -> Option<f64> {
    let ExprNode::Add(children) = arena.node(id) else {
        // (A small part within 64 bits shows at any working precision.)
        return match exact::operand(arena, id, exact) {
            Some(z) if z.im.is_zero() && input_bits(&z.re) >= 64 => rational_small_part(&z.re),
            _ => None,
        };
    };
    let total = cache.get(&id)?;
    let tb = errs.get(&id)?;
    if tb.is_unknown() || accuracy::contains_zero(total, tb.joint()) {
        return None;
    }
    let smallest = children
        .iter()
        .filter_map(|c| {
            let (v, b) = (cache.get(c)?, errs.get(c)?);
            (!b.is_unknown() && !accuracy::contains_zero(v, b.joint())).then(|| accuracy::lg_abs(v))
        })
        .fold(f64::INFINITY, f64::min);
    let ratio = smallest - accuracy::lg_abs_low(total);
    ratio.is_finite().then_some(ratio)
}

/// `log₂` of `abs(n)` (within `2⁻⁵²` relative, or a bit beyond `f64`).
fn lg_int(n: &BigInt) -> f64 {
    use num_traits::{Signed, ToPrimitive};
    match n.abs().to_f64() {
        Some(f) if f.is_finite() && f > 0.0 => f.log2(),
        _ => n.bits() as f64,
    }
}

/// `log₂ abs(h/u)` for an integer `n = u + h` whose leading `k` binary
/// (`k ≤ 64`) or decimal (`k ≤ 8`) digits are `u` and whose rest `h ≠ 0` lies
/// at least 64 bits below the unit of the `k`-th digit: `10⁴⁰⁰ + 1` is `u =
/// 10⁴⁰⁰`, `h = 1`.  Integers below 128 bits have no such part.
fn integer_small_part(n: &BigInt) -> Option<f64> {
    use num_integer::Integer;
    use num_traits::Signed;
    let a = n.abs();
    let bits = a.bits();
    if bits < 128 {
        return None;
    }
    // `u = round(a/g)·g` for the unit `g` of the k-th digit.
    let split = |g: &BigInt| -> Option<Option<f64>> {
        let (quot, rem) = a.div_mod_floor(g);
        let up = &rem + &rem >= *g;
        let u = if up { (quot + 1u32) * g } else { quot * g };
        let h = &a - &u;
        if h.is_zero() {
            // `n` is short: no small part.
            return Some(None);
        }
        (lg_int(&h) < lg_int(g) - 64.0).then(|| Some(lg_int(&h) - lg_int(&u)))
    };
    for k in 1..=64u64 {
        let g = BigInt::from(1u32) << (bits - k);
        if let Some(found) = split(&g) {
            return found;
        }
    }
    let digits = (bits as f64 * std::f64::consts::LOG10_2).floor() as u32 + 1;
    for k in 1..=8u32 {
        let Some(e) = digits.checked_sub(k).filter(|&e| e > 0) else {
            break;
        };
        if let Some(found) = split(&BigInt::from(10u32).pow(e)) {
            return found;
        }
    }
    None
}

/// `log₂ abs(h/u)` for an exact rational `x = u + h` with a small part `h`
/// (the largest found): a small part of its numerator or denominator
/// ([`integer_small_part`]: `(10³⁰⁰ + 1)/10³⁰⁰`), or `u ≠ 0` the last
/// convergent of its continued fraction before a partial quotient `a ≥ 2¹⁶`
/// (among the first 64), so `abs(h) ≈ 1/(b²·a)` for `u = p/b` (within a
/// bit).  `1 + 10⁻³⁰⁰` is `1 + h`, `log₂ abs(h) = −996.6`; `10⁻³⁰⁰` itself
/// (`u = 0`) and `1234567/7654321` have none.
fn rational_small_part(x: &crate::base::numeric::Q) -> Option<f64> {
    use num_integer::Integer;
    if x.is_zero() {
        return None;
    }
    let digits = [x.numer(), x.denom()]
        .into_iter()
        .filter_map(integer_small_part)
        .fold(None, |acc: Option<f64>, r| {
            Some(acc.map_or(r, |a| a.max(r)))
        });
    let lg = lg_int;
    let (mut n, mut d) = (x.numer().clone(), x.denom().clone());
    // The convergents `pₖ/qₖ` and the ones before.
    let (mut p, mut q) = (BigInt::from(1), BigInt::from(0));
    let (mut p_prev, mut q_prev) = (BigInt::from(0), BigInt::from(1));
    for step in 0..64 {
        if d.is_zero() {
            return digits;
        }
        let (a, r) = n.div_mod_floor(&d);
        if step > 0 && a.bits() >= 16 && !p.is_zero() {
            let lg_u = lg(&p) - lg(&q);
            let lg_h = -(2.0 * lg(&q) + lg(&a));
            let cf = lg_h - lg_u;
            return Some(digits.map_or(cf, |d| d.max(cf)));
        }
        let next_p = &a * &p + &p_prev;
        let next_q = &a * &q + &q_prev;
        p_prev = std::mem::replace(&mut p, next_p);
        q_prev = std::mem::replace(&mut q, next_q);
        n = std::mem::replace(&mut d, r);
    }
    digits
}

/// Record in `slot` the second-order term that a power `(a + h)^q` or a
/// product `(a + h)·(b + k)` of sums with small parts loses below its error
/// bound `2^radius` ([`accuracy::Absorbed`]): `q(q − 1)/2·a^q·(h/a)²`, and
/// `ab·(h/a)·(k/b)`.  A cancellation of the leading and first-order terms
/// leaves it: `(√2 + 10⁻⁴⁰⁰)²·(sin²1 + cos²1) − 2 − 2√2·10⁻⁴⁰⁰` is
/// `10⁻⁸⁰⁰` (before 0.35 it printed `0`).  The same for an analytic
/// function at an argument with a small part, `f″(a)·h²/2` (taken as
/// `max(abs(f(a + h)), 1)·(h/a)²`), and for an exact rational `a + h` the
/// canonical form folded into one number ([`rational_small_part`]): before
/// 0.36 `sin(1 + 10⁻³⁰⁰) + sin(1 − 10⁻³⁰⁰) − 2·sin 1` (truly `−sin 1·10⁻⁶⁰⁰`),
/// `log(1 + 10⁻³⁰⁰) + log(1 − 10⁻³⁰⁰)` (`−10⁻⁶⁰⁰`) and `(1 + 10⁻⁴⁰⁰)^(1/2) − 1 −
/// 10⁻⁴⁰⁰/2` (`−10⁻⁸⁰⁰/8`) printed `0`: the inputs are held in full at
/// about 1,000 or 1,330 bits ([`input_bits`]), and the value needs twice as
/// many.
#[allow(clippy::too_many_arguments)]
fn note_cross_terms(
    arena: &Arena,
    id: ExprId,
    value: &Complex,
    radius: accuracy::ErrExp,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    exact: &exact::ExactMap,
    slot: &mut Option<accuracy::Absorbed>,
) {
    if !radius.is_finite() {
        return;
    }
    let lv = accuracy::lg_abs(value);
    if !lv.is_finite() {
        return;
    }
    let lost = match arena.node(id) {
        ExprNode::Pow(b, e) => {
            let Some(q) = arena
                .as_num(*e)
                .and_then(crate::base::numeric::ratio_to_f64)
            else {
                return;
            };
            let Some(r) = small_part(arena, *b, cache, errs, exact) else {
                return;
            };
            let c = (q * (q - 1.0) / 2.0).abs();
            if c == 0.0 || r > -8.0 {
                return;
            }
            lv + c.log2() + 2.0 * r
        }
        ExprNode::Mul(children) => {
            let mut parts: Vec<f64> = children
                .iter()
                .filter_map(|&c| small_part(arena, c, cache, errs, exact))
                .filter(|&r| r <= -8.0)
                .collect();
            if parts.len() < 2 {
                return;
            }
            parts.sort_by(f64::total_cmp);
            lv + parts[parts.len() - 1] + parts[parts.len() - 2]
        }
        ExprNode::Sin(c)
        | ExprNode::Cos(c)
        | ExprNode::Tan(c)
        | ExprNode::Exp(c)
        | ExprNode::Ln(c)
        | ExprNode::Asin(c)
        | ExprNode::Acos(c)
        | ExprNode::Atan(c)
        | ExprNode::Sinh(c)
        | ExprNode::Cosh(c)
        | ExprNode::Tanh(c)
        | ExprNode::Asinh(c)
        | ExprNode::Acosh(c)
        | ExprNode::Atanh(c)
        | ExprNode::Gamma(c)
        | ExprNode::LogGamma(c)
        | ExprNode::Digamma(c)
        | ExprNode::Erf(c)
        | ExprNode::Erfc(c)
        | ExprNode::LambertW(c)
        | ExprNode::Si(c)
        | ExprNode::Ci(c)
        | ExprNode::Ei(c)
        | ExprNode::Li(c)
        | ExprNode::Zeta(c)
        | ExprNode::Factorial(c) => {
            let Some(r) = small_part(arena, *c, cache, errs, exact) else {
                return;
            };
            if r > -8.0 {
                return;
            }
            lv.max(0.0) + 2.0 * r
        }
        _ => return,
    };
    accuracy::Absorbed::note(slot, lost, radius);
}

/// Is the node `node`, evaluated to `value ± e`, without a value or a bound
/// only because its arguments' error balls are too wide — its bound unknown
/// or its value not finite while every argument has a finite value with a
/// bound, at least one of them inexact?  Such a node needs more precision in
/// its arguments, not in itself: a quotient of two differences that are 0
/// at the working precision (`(e^ε − 1)/(e^{2ε} − 1)`, `ε = 10⁻⁴⁵`), a
/// function at an argument that cancelled to 0 or onto a pole
/// (`erfc⁻¹(sin(1 + 10⁻¹⁵⁰) − sin 1)`), the side of a branch cut decided
/// by a part within its error of 0, a condition at its threshold.  An
/// argument that underflowed is not: below the exponent range no precision
/// resolves it.  (See [`evaluate_adaptive`], which pursues such a value as
/// it pursues a root that is zero to the working precision.)
fn precision_limited(
    node: &ExprNode,
    value: &Complex,
    e: accuracy::Bound,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
) -> bool {
    let finite = |z: &Complex| !(z.0.is_inf() || z.0.is_nan() || z.1.is_inf() || z.1.is_nan());
    if !e.is_unknown() && finite(value) {
        return false;
    }
    let mut inexact = false;
    for c in node.children() {
        let (Some(v), Some(b)) = (cache.get(&c), errs.get(&c)) else {
            continue;
        };
        if b.is_unknown() || !finite(v) || accuracy::is_underflow(b.joint()) {
            return false;
        }
        inexact |= !b.is_exact();
    }
    inexact
}

/// The error of a node whose value `value` has an infinite part although
/// its arguments are finite: the value overflows the exponent range of
/// `BigFloat` (`Γ(10²⁰/3)`, `exp(10¹⁶)`, a product of such numbers), or is
/// the reciprocal of an argument that underflowed below it.  `None` when
/// the value is finite, or infinite for another reason (a division by an
/// argument that is only 0 to the working precision, which more precision
/// may resolve, see [`precision_limited`]).  Before 0.31 the infinite value
/// propagated to a `PrecisionExhausted`: `Γ(10²⁰/3)` "achieved 0 digits",
/// while `uppergamma(10²⁰/3, 10²⁰/3)` reported its overflow.
fn exponent_range_error(
    arena: &Arena,
    id: ExprId,
    value: &Complex,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
) -> Option<SymplexError> {
    if !(value.0.is_inf() || value.1.is_inf()) {
        return None;
    }
    let node = arena.node(id);
    let what = match node {
        ExprNode::Exp(_) => "exp",
        ExprNode::Pow(..) => "a power",
        ExprNode::Mul(_) => "a product",
        ExprNode::Add(_) => "a sum",
        ExprNode::Gamma(_) => "Gamma",
        ExprNode::Factorial(_) => "factorial",
        ExprNode::Binomial(..) => "binomial",
        ExprNode::Beta(..) => "beta",
        ExprNode::Sinh(_) => "sinh",
        ExprNode::Cosh(_) => "cosh",
        ExprNode::Ei(_) => "Ei",
        // The functions that grow like an exponential or a factorial, and
        // have no pole at a finite nonzero argument.
        ExprNode::Apply(sid, _) => match arena.lib_fn(*sid) {
            Some(LibFn::Erfi) => "erfi",
            Some(LibFn::Shi) => "Shi",
            Some(LibFn::Chi) => "Chi",
            Some(LibFn::BesselI) => "besseli",
            Some(LibFn::AiryBi) => "airybi",
            Some(LibFn::AiryBiPrime) => "airybiprime",
            Some(LibFn::RisingFactorial) => "rising_factorial",
            Some(LibFn::Subfactorial) => "subfactorial",
            _ => return None,
        },
        _ => return None,
    };
    let mut lg_sum = 0.0f64;
    for c in node.children() {
        let Some(v) = cache.get(&c) else {
            continue;
        };
        if v.0.is_inf() || v.0.is_nan() || v.1.is_inf() || v.1.is_nan() {
            return None;
        }
        if accuracy::mag(v).is_none() {
            let b = errs.get(&c).copied().unwrap_or(accuracy::Bound::UNKNOWN);
            // An exact 0 is a parameter (`besseli(0, x)`); an inexact one
            // may be a division by a difference that cancelled, which more
            // precision resolves (`precision_limited`).
            if b.is_exact() {
                continue;
            }
            let underflow = accuracy::is_underflow(b.joint());
            return underflow.then(|| SymplexError::Unevaluable {
                reason: format!(
                    "{what}: an argument underflows the arbitrary-precision exponent range \
                     (below 2^{:e}), and its reciprocal overflows it",
                    f64::from(astro_float::EXPONENT_MIN)
                ),
            });
        }
        lg_sum += accuracy::lg_abs(v);
    }
    // The magnitude where it is cheap to estimate.
    let lg = match node {
        ExprNode::Exp(a) => cache
            .get(a)
            .and_then(|v| bigfloat_to_f64_rounded(&v.0, RoundingMode::ToEven).ok())
            .map(|x| x * std::f64::consts::LOG2_E),
        ExprNode::Gamma(a) | ExprNode::Factorial(a) => cache
            .get(a)
            .and_then(|v| bigfloat_to_f64_rounded(&v.0, RoundingMode::ToEven).ok())
            .filter(|x| *x > 1.0)
            .map(|x| {
                let x = if matches!(node, ExprNode::Factorial(_)) {
                    x + 1.0
                } else {
                    x
                };
                ((x - 0.5) * x.ln() - x) * std::f64::consts::LOG2_E
            }),
        ExprNode::Mul(_) => Some(lg_sum),
        _ => None,
    }
    .filter(|lg| lg.is_finite() && *lg > f64::from(astro_float::EXPONENT_MAX) / 2.0);
    Some(SymplexError::Unevaluable {
        reason: match lg {
            Some(lg) => format!(
                "{what}: the value (about 2^{lg:.3e}) overflows the arbitrary-precision exponent range"
            ),
            None => format!("{what}: the value overflows the arbitrary-precision exponent range"),
        },
    })
}

/// The error of node `node`, which failed with `e`: when `e` is only the
/// absence of a child's value (a child that failed and was skipped, see
/// [`evaluate_tree`]), the child's own error.  Before 0.30 the parent
/// reported the cache miss: `harmonic(7/2) + 1` was "sub-expression e22 not
/// in cache (likely contains free symbols)".
fn root_cause(
    node: &ExprNode,
    e: SymplexError,
    failed: &FxHashMap<ExprId, SymplexError>,
) -> SymplexError {
    if let SymplexError::Unevaluable { reason } = &e {
        for c in node.children() {
            if let Some(child_error) = failed.get(&c)
                && *reason == not_evaluated_reason(c)
            {
                return duplicate_error(child_error);
            }
        }
    }
    e
}

/// A copy of an evaluation error (`SymplexError` is not `Clone`): the
/// variants `evalf` raises field for field, any other by its message.
fn duplicate_error(e: &SymplexError) -> SymplexError {
    match e {
        SymplexError::PrecisionExhausted {
            requested,
            achieved,
        } => SymplexError::PrecisionExhausted {
            requested: *requested,
            achieved: *achieved,
        },
        SymplexError::FreeSymbol { name } => SymplexError::FreeSymbol { name: name.clone() },
        SymplexError::Unevaluable { reason } => SymplexError::Unevaluable {
            reason: reason.clone(),
        },
        SymplexError::ComputationFailed { operation, reason } => SymplexError::ComputationFailed {
            operation,
            reason: reason.clone(),
        },
        SymplexError::NotImplemented(s) => SymplexError::NotImplemented(s.clone()),
        SymplexError::Divergent { operation, reason } => SymplexError::Divergent {
            operation,
            reason: reason.clone(),
        },
        other => SymplexError::Unevaluable {
            reason: other.to_string(),
        },
    }
}

/// Is `node` a condition (a truth value, not a number)?
fn is_condition(node: &ExprNode) -> bool {
    matches!(
        node,
        ExprNode::BoolTrue
            | ExprNode::BoolFalse
            | ExprNode::Gt(_, _)
            | ExprNode::Ge(_, _)
            | ExprNode::Eq_(_, _)
            | ExprNode::Ne(_, _)
            | ExprNode::And(_)
            | ExprNode::Or(_)
            | ExprNode::Not(_)
    )
}

/// Evaluate node `id` from its children's values (`cache`) and error bounds
/// (`errs`): its value and error bound.
///
/// Most nodes are evaluated by [`eval_node`] and bounded from their
/// children by [`accuracy::node_error`].  `+` and `·` are evaluated with
/// their per-part bounds in one pass ([`accuracy::add_with_bound`],
/// [`accuracy::mul_with_bound`]: the roundings of the partial results are
/// part of the bound).  The nodes whose evaluator knows more than the
/// children's values report their own bound: sums and products (their
/// terms' bounds; an infinite sum's tail), `RootOf` and `RootSum` (certified
/// inclusion disks of the roots), `Piecewise` (whether its conditions were
/// decided with certainty), physical constants (their value's bound) and
/// definite integrals (the quadrature's error estimate).
fn eval_node_with_error(
    arena: &Arena,
    id: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    let (value, err) = match arena.node(id) {
        ExprNode::Add(children) | ExprNode::Mul(children) => {
            let mut parts: Vec<(&Complex, accuracy::Bound)> = Vec::with_capacity(children.len());
            for &c in children.iter() {
                let v = get_cached(cache, c)?;
                parts.push((v, errs.get(&c).copied().unwrap_or(accuracy::Bound::UNKNOWN)));
            }
            return Ok(if matches!(arena.node(id), ExprNode::Add(_)) {
                accuracy::add_with_bound(&parts, prec, rm)
            } else {
                accuracy::mul_with_bound(&parts, prec, rm)
            });
        }
        ExprNode::Sum(body, var, lo, hi) => {
            eval_sum(arena, *body, *var, *lo, *hi, cache, prec, rm, cc)?
        }
        ExprNode::Product_(body, var, lo, hi) => {
            eval_product(arena, *body, *var, *lo, *hi, cache, prec, rm, cc)?
        }
        ExprNode::Piecewise(pairs) => eval_piecewise(arena, pairs, cache, errs, prec, rm, cc)?,
        ExprNode::RootOf(poly, var, index) => eval_rootof(arena, *poly, *var, *index, prec)?,
        ExprNode::RootSum(poly, body, sumvar) => {
            eval_rootsum(arena, *poly, *body, *sumvar, prec, rm, cc)?
        }
        ExprNode::DefiniteIntegral(body, var, lo, hi) => {
            eval_definite_integral(arena, *body, *var, *lo, *hi, cache, errs, prec)?
        }
        node if inverse_identity(arena, node, cache, errs, prec, rm).is_some() => {
            let u = inverse_identity(arena, node, cache, errs, prec, rm).unwrap_or(id);
            return Ok((
                get_cached(cache, u)?.clone(),
                errs.get(&u).copied().unwrap_or(accuracy::Bound::UNKNOWN),
            ));
        }
        // Lambert W reports its own bound (complex arguments, every branch).
        node if lambertw::lambert_parts(arena, node).is_some() => {
            let value = match eval_node(arena, id, cache, prec, rm, cc) {
                Ok(value) => value,
                // `W_k(0)` for `k ≠ 0` at an argument only 0 to the working
                // precision: no value yet (as in the arm below).
                Err(SymplexError::Unevaluable { .. }) if inexact_zero_child(node, cache, errs) => {
                    return Ok((c_zero(prec), accuracy::Bound::UNKNOWN));
                }
                Err(e) => return Err(e),
            };
            let err = match lambertw::lambert_parts(arena, node) {
                Some(Ok((x, k))) => {
                    let bz = errs.get(&x).copied().unwrap_or(accuracy::Bound::UNKNOWN);
                    lambertw::error_bound(get_cached(cache, x)?, bz, &value, k, prec)
                }
                _ => accuracy::Bound::UNKNOWN,
            };
            (value, err)
        }
        // `loggamma` of a non-real argument reports its own bound (the
        // sensitivity rules are for real arguments).
        ExprNode::LogGamma(c) if cache.get(c).is_some_and(|v| !v.1.is_zero()) => {
            let value = eval_node(arena, id, cache, prec, rm, cc)?;
            let bz = errs.get(c).copied().unwrap_or(accuracy::Bound::UNKNOWN);
            let err = loggamma::error_bound(get_cached(cache, *c)?, bz, &value, prec);
            (value, err)
        }
        // `polylog` off the real interval [−1, 1] reports its own bound (the
        // sensitivity rules are for real arguments; `polylog.rs`).
        node @ ExprNode::Apply(_, args) if polylog::is_general(arena, node, cache) => {
            let value = match eval_node(arena, id, cache, prec, rm, cc) {
                Ok(value) => value,
                // An argument that cancelled to 0 or rounded onto 1 (as in
                // the arm below).
                Err(SymplexError::Unevaluable { .. })
                    if inexact_zero_child(node, cache, errs)
                        || rounded_onto_pole(arena, node, cache, errs) =>
                {
                    return Ok((c_zero(prec), accuracy::Bound::UNKNOWN));
                }
                Err(e) => return Err(e),
            };
            let bound = |c: ExprId| errs.get(&c).copied().unwrap_or(accuracy::Bound::UNKNOWN);
            let err = polylog::error_bound(
                &get_cached(cache, args[0])?.0,
                bound(args[0]),
                get_cached(cache, args[1])?,
                bound(args[1]),
                &value,
                prec,
                rm,
                cc,
            );
            (value, err)
        }
        // `polylog` of a complex order reports its own bound.
        node @ ExprNode::Apply(_, args) if polylog::is_complex_order(arena, node, cache) => {
            let value = eval_node(arena, id, cache, prec, rm, cc)?;
            let bound = |c: ExprId| errs.get(&c).copied().unwrap_or(accuracy::Bound::UNKNOWN);
            let err = polylog::complex_order_bound(
                get_cached(cache, args[0])?,
                bound(args[0]),
                get_cached(cache, args[1])?,
                bound(args[1]),
                &value,
                prec,
            );
            (value, err)
        }
        ExprNode::PhysicalConstant(_, value_id) => match cache.get(value_id) {
            // The constant is an atom to every tree walk, so its stored
            // value (`h/(2π)` for ħ) was never visited: evaluate it as a
            // subtree of its own unless it is a single already-cached node.
            Some(v) => (
                v.clone(),
                errs.get(value_id)
                    .copied()
                    .unwrap_or(accuracy::Bound::UNKNOWN),
            ),
            None => {
                let order = walk::post_order_ids(arena, *value_id);
                evaluate_tree(arena, *value_id, &order, None, true, prec, rm, cc)?
            }
        },
        _ => {
            let value = match eval_node(arena, id, cache, prec, rm, cc) {
                Ok(value) => value,
                // A domain error at 0 (`Ci(0)`, `arg(0)`) for an argument
                // that is only 0 to the working precision says nothing
                // about the true argument: no value is known yet, and the
                // evaluation is repeated at a higher precision.  Before 0.29
                // `Ci(−(exp(10⁻³⁰) − 1 − 10⁻³⁰))` was `Unevaluable: Ci(0) is
                // −∞`.  Nor does a pole met by an inexact argument that
                // rounded onto it (`ζ(1 + 10⁻⁴⁵)`: `1 + 10⁻⁴⁵` is 1 at 128
                // bits).
                Err(SymplexError::Unevaluable { .. })
                    if inexact_zero_child(arena.node(id), cache, errs)
                        || rounded_onto_pole(arena, arena.node(id), cache, errs) =>
                {
                    return Ok((c_zero(prec), accuracy::Bound::UNKNOWN));
                }
                Err(e) => return Err(e),
            };
            let err = accuracy::node_error(arena, id, &value, cache, errs, prec, || {
                sensitivity::special_error(arena, id, &value, cache, errs, prec, rm, cc)
            });
            return Ok((value, err));
        }
    };
    let err = accuracy::reported(&value, err, prec);
    Ok((value, err))
}

/// `f(g(u)) = u` for a function `f` and the principal branch `g` of its
/// inverse — `sin∘asin`, `cos∘acos`, `tan∘atan`, `sinh∘asinh`, `cosh∘acosh`,
/// `tanh∘atanh`, `exp∘ln` — an identity on all of ℂ (where `g(u)` is defined:
/// the inner node must have evaluated): `u`, when `node` is such a
/// composition.  The value is then `u`'s, with `u`'s bound.  Numerically
/// `sin(asin(7/5·√2/√(24/25)))` is `sin(π/2 − 1.29i)`, whose imaginary part
/// `cos(π/2)·sinh(−1.29)` is 0 only to within its error, and the square root
/// of `1 − ½·sin²(…)` (a negative number) then had an undecidable side of its
/// cut (Rubi's antiderivatives with `elliptic_f(asin(…), m)`).
///
/// Where the inner function has a singular point the identity needs `u`'s
/// error ball to exclude it: `ln 0`, `atan(±i)` and `atanh(±1)` are
/// infinite, and `exp(ln 0) = exp(zoo)` has no value.  Before 0.30
/// `exp(ln((1 + √2)² − 3 − 2√2))` (a zero the canonical form does not see)
/// took the value of the zero ball and printed `0`.
fn inverse_identity(
    arena: &Arena,
    node: &ExprNode,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    prec: usize,
    rm: RoundingMode,
) -> Option<ExprId> {
    let (outer, inner) = match node {
        ExprNode::Sin(a)
        | ExprNode::Cos(a)
        | ExprNode::Tan(a)
        | ExprNode::Sinh(a)
        | ExprNode::Cosh(a)
        | ExprNode::Tanh(a)
        | ExprNode::Exp(a) => (node, *a),
        _ => return None,
    };
    let u = match (outer, arena.node(inner)) {
        (ExprNode::Sin(_), ExprNode::Asin(u))
        | (ExprNode::Cos(_), ExprNode::Acos(u))
        | (ExprNode::Tan(_), ExprNode::Atan(u))
        | (ExprNode::Sinh(_), ExprNode::Asinh(u))
        | (ExprNode::Cosh(_), ExprNode::Acosh(u))
        | (ExprNode::Tanh(_), ExprNode::Atanh(u))
        | (ExprNode::Exp(_), ExprNode::Ln(u)) => *u,
        _ => return None,
    };
    if !cache.contains_key(&inner) {
        return None;
    }
    let uv = cache.get(&u)?;
    let singular: &[(i32, i32)] = match outer {
        ExprNode::Exp(_) => &[(0, 0)],
        ExprNode::Tan(_) => &[(0, 1), (0, -1)],
        ExprNode::Tanh(_) => &[(1, 0), (-1, 0)],
        _ => &[],
    };
    if !singular.is_empty() {
        let err = errs
            .get(&u)
            .copied()
            .unwrap_or(accuracy::Bound::UNKNOWN)
            .joint();
        if accuracy::is_unknown(err) {
            return None;
        }
        for &(a, b) in singular {
            let d = (
                uv.0.sub(&BigFloat::from_i32(a, prec), prec, rm),
                uv.1.sub(&BigFloat::from_i32(b, prec), prec, rm),
            );
            // One bit for the rounding of the difference.
            if accuracy::contains_zero(&d, accuracy::shift(err, 1.0)) {
                return None;
            }
        }
    }
    Some(u)
}

/// Is `node` a function with poles at integers (`Γ`, `ζ`, …) whose
/// argument is an integer at the working precision without being exact?
/// Or one with a singular point elsewhere — `Li_s(1)`, `K(1)`, `Π(1, m)`,
/// `Π(n, 1)`, `erfc⁻¹(2)`, `erf⁻¹(±1)` — met by an argument that rounded
/// onto it (before 0.31 `polylog(1/3, 1 − 10⁻⁴⁰)` was "`polylog(s, 1)`
/// diverges" at 16 digits: `1 − 10⁻⁴⁰` is 1 at 128 bits)?
fn rounded_onto_pole(
    arena: &Arena,
    node: &ExprNode,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
) -> bool {
    if let ExprNode::Apply(sid, _) = node {
        let args = node.children();
        // Is argument `k` an inexact real value equal to one of `points`?
        let at = |k: usize, points: &[i32]| -> bool {
            args.get(k).is_some_and(|c| {
                let inexact = !errs
                    .get(c)
                    .copied()
                    .unwrap_or(accuracy::Bound::UNKNOWN)
                    .is_exact();
                inexact
                    && cache.get(c).is_some_and(|v| {
                        v.1.is_zero()
                            && points
                                .iter()
                                .any(|&p| v.0.cmp(&BigFloat::from_i32(p, 64)) == Some(0))
                    })
            })
        };
        match arena.lib_fn(*sid) {
            Some(LibFn::PolyLog) => return at(1, &[1]),
            Some(LibFn::EllipticK) => return at(0, &[1]),
            Some(LibFn::EllipticPi) => return at(0, &[1]) || at(1, &[1]),
            Some(LibFn::ErfcInv) => return at(0, &[2]),
            Some(LibFn::ErfInv) => return at(0, &[-1, 1]),
            _ => {}
        }
    }
    let poles = match node {
        ExprNode::Gamma(_)
        | ExprNode::LogGamma(_)
        | ExprNode::Digamma(_)
        | ExprNode::Polygamma(_, _)
        | ExprNode::Zeta(_)
        | ExprNode::Factorial(_)
        | ExprNode::Beta(_, _)
        | ExprNode::Binomial(_, _) => true,
        ExprNode::Apply(sid, _) => matches!(
            arena.lib_fn(*sid),
            Some(LibFn::RisingFactorial | LibFn::FallingFactorial | LibFn::Harmonic)
        ),
        _ => false,
    };
    poles
        && node.children().into_iter().any(|c| {
            cache.get(&c).is_some_and(|v| v.1.is_zero() && v.0.is_int())
                && !errs
                    .get(&c)
                    .copied()
                    .unwrap_or(accuracy::Bound::UNKNOWN)
                    .is_exact()
        })
}

/// Does `node` have a child whose value is 0 without being exactly 0?
fn inexact_zero_child(node: &ExprNode, cache: &FxHashMap<ExprId, Complex>, errs: &ErrMap) -> bool {
    node.children().into_iter().any(|c| {
        cache.get(&c).is_some_and(|v| {
            accuracy::mag(v).is_none()
                && !errs
                    .get(&c)
                    .copied()
                    .unwrap_or(accuracy::Bound::UNKNOWN)
                    .is_exact()
        })
    })
}

/// How far [`evaluate_adaptive`] pursues a value that is zero to the working
/// precision (its error ball contains 0 and shrinks with the precision, or
/// the value itself falls with every increase in precision) before it is
/// returned as 0.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ZeroSearch {
    /// To the cap of every evaluation, twice the working precision plus 256
    /// bits: the internal callers of [`evalf_complex`] and
    /// [`eval_const_f64`], which compare the value against a tolerance (the
    /// integrator's `F′ − f` check) and meet true zeros all the time.
    Cap,
    /// [`ZERO_SEARCH_BITS`] beyond the working precision: the zero and sign
    /// tests of the crate that go beyond the cap (`solve`, `polysys`,
    /// `poly::algebraic`), whose candidates are exact algebraic numbers.
    Deep,
    /// As [`Deep`](ZeroSearch::Deep), and at least to the precision that
    /// holds every exact rational of the expression in full (see
    /// [`input_bits`]): results read as numbers ([`evalf`], `Ex::eval_f64`,
    /// `Ex::eval_complex64`), where a 0 that is really `2.5·10⁻¹⁴⁹` is a
    /// wrong answer.
    Number,
}

/// The bits that hold the rational `p/q` in full: `max(bits(p), bits(q))`,
/// or the bits of the odd part of `p` over a power of two (a float of that
/// many bits holds it exactly).  A zero to a precision below the largest of
/// these over the exact values of an expression may be the rounding of an
/// input: `sin(2/3 + 10⁻²⁰⁰⁰) − sin(2/3)` is the difference of two equal
/// floats below 6,646 bits (before 0.35 it printed `0`).
fn input_bits(q: &crate::base::numeric::Q) -> u64 {
    let (p, d) = (q.numer(), q.denom());
    if d.bits() == d.trailing_zeros().unwrap_or(0) + 1 {
        p.bits() - p.trailing_zeros().unwrap_or(0)
    } else {
        p.bits().max(d.bits())
    }
}

/// The bits that hold the second-order part of an exact rational `u + h`
/// with a small part ([`rational_small_part`]): `2·log₂ abs(u/h)`.  Held to
/// [`input_bits`] only, `u·(1 + h/u + O((h/u)²))` loses its `(h/u)²` term,
/// which a cancellation of the first two leaves: before 0.36 `(1 +
/// 10⁻⁷⁰⁰)⁻¹·((√2 + √3)² − 2√6)/5 − 1 + 10⁻⁷⁰⁰` (truly `10⁻¹⁴⁰⁰`; the
/// canonical form holds `10⁷⁰⁰/(5·(10⁷⁰⁰ + 1))` and `1 − 10⁻⁷⁰⁰`, in full
/// at 2,328 bits, agreeing to 4,651) printed `0`.  0 for a rational without
/// one, below 256 bits, or beyond the configured maximum precision (refused
/// as it is).
fn second_order_bits(q: &crate::base::numeric::Q, arena: &Arena) -> u64 {
    // Below 256 bits the second-order part lies within the zero search of
    // every evaluation ([`ZERO_SEARCH_BITS`]).
    let bits = input_bits(q);
    if !(256..=u64::from(arena.config.max_evalf_precision)).contains(&bits) {
        return 0;
    }
    rational_small_part(q).map_or(0, |r| (-2.0 * r).ceil().max(0.0) as u64)
}

/// Bits beyond the working precision to which [`ZeroSearch::Deep`] pursues
/// a value that is zero to the precision reached (≈ 308 decimal digits of
/// cancellation).  A tiny value hidden by the cancellation of larger terms
/// has no digits until the precision exceeds the depth of the
/// cancellation, `mag(terms) − mag(value)`, and nothing before that
/// distinguishes it from a true zero; the search doubles the precision.
/// A true zero — met all the time, by every `solve` candidate check — pays
/// one evaluation at about this many bits, which bounds the budget: 3,072
/// bits made one `solve_general` fixture of the SymPy oracle (17 true-zero
/// checks) take 6 s in a debug build.  Deeper cancellations are avoided
/// at their source (`eval` keeps `polygamma(n, p/q)` symbolic when its
/// closed form would cancel more than 200 bits).  Before 0.30 the search
/// stopped at the cap of the digits: `1/2 − erf(13√2)/2` (`2.476·10⁻¹⁴⁹`,
/// 493 bits of cancellation) was `0.0` from `eval_f64`.
pub(crate) const ZERO_SEARCH_BITS: usize = 1024;

/// How a value returned by [`evaluate_adaptive`] was settled.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Settled {
    /// Every part the value shows carries the requested digits (an exact
    /// zero included).
    Certified,
    /// Zero to the precision reached: the true value is within the error
    /// bound of the last evaluation, and not known to be 0.
    ZeroToPrecision,
}

/// How [`evaluate_adaptive`] ended.
enum Adaptive {
    /// A value, and how it was settled.
    Settled(Complex, Settled),
    /// A number that is certainly not 0 came out 0 below the exponent
    /// range of `BigFloat` (`besselk(0, 10¹⁰) ≈ 1.2·10^(−4342944824)`):
    /// no digit of it is known ([`underflow_error`]), at most its sign.
    Underflow(accuracy::Nonzero),
    /// A number below the exponent range known to the requested digits
    /// scaled (`extended`): `m·2^k` (`erfc(10⁵)`, `exp(−10¹⁰) −
    /// exp(−2·10¹⁰)`).  Not printed ([`underflow_error`]), but its sign
    /// and direction are known.
    Beyond(extended::Scaled),
    /// 0 within the underflow bound and not known to be nonzero: a sum of
    /// such numbers of both signs without a scaled form (`besselk(0, 10¹⁰)
    /// − airyai(10⁷)`) — no precision decides it ([`undecided_error`]).
    Undecided,
    /// Zero to the precision reached, but a sum lost a term that is
    /// certainly not 0 below its error bound ([`accuracy::Absorbed`]) and no
    /// precision within the limit keeps it: `below_range` — the term lies
    /// below the exponent range (`sin²1 + cos²1 − 1 + e^(−10¹⁰)`,
    /// [`hidden_error`]); otherwise it needs more than the configured maximum
    /// precision.  Not known to be 0: if the rest cancels exactly, the value is
    /// the lost term.
    Hidden { below_range: bool },
}

/// The error of a decimal result that is zero to the precision reached
/// while a nonzero term below the exponent range was lost in it
/// ([`Adaptive::Hidden`]).  Before 0.35 it printed `0`:
/// `sin²1 + cos²1 − 1 + e^(−10¹⁰)` (truly `e^(−10¹⁰)`).
fn hidden_error() -> SymplexError {
    SymplexError::Unevaluable {
        reason: format!(
            "the value is 0 to the precision reached, but a term that is not 0 and lies below the \
             arbitrary-precision exponent range (2^{:e}) was lost in a cancellation: not known \
             to be 0",
            f64::from(astro_float::EXPONENT_MIN)
        ),
    }
}

/// The error of a decimal result that is zero to the precision reached
/// while a nonzero term was lost below its error bound deeper than the
/// configured maximum precision reaches ([`Adaptive::Hidden`]).
fn hidden_deep_error(digits: u32) -> SymplexError {
    SymplexError::PrecisionExhausted {
        requested: digits,
        achieved: 0,
    }
}

/// The error of a decimal result that is 0 within the underflow bound and
/// not known to be anything ([`Adaptive::Undecided`]).  Before 0.34 it was
/// printed `0`, and so was a sum of scaled values of both signs:
/// `exp(−10¹⁰) − exp(−2·10¹⁰)`.
fn undecided_error() -> SymplexError {
    SymplexError::Unevaluable {
        reason: format!(
            "the value underflows the arbitrary-precision exponent range (its magnitude is \
             below 2^{:e}) and is not known to be 0 or not: a sum of such values of both signs",
            f64::from(astro_float::EXPONENT_MIN)
        ),
    }
}

/// The error of a decimal result that is a nonzero number below the
/// exponent range ([`Adaptive::Underflow`]).  mpmath, with unbounded
/// exponents, prints `erfc(10⁵)` as `5.2e-4342944825`; before 0.32 `evalf`
/// printed `0`, a digit that is not correct.  (The `f64` routes return
/// `0.0`, the correctly rounded `f64` of such a number.)
fn underflow_error() -> SymplexError {
    SymplexError::Unevaluable {
        reason: format!(
            "the value is not 0 but underflows the arbitrary-precision exponent range \
             (its magnitude is below 2^{:e})",
            f64::from(astro_float::EXPONENT_MIN)
        ),
    }
}

/// Evaluate `expr` to `digits` correct significant digits.
///
/// The value is computed at [`working_precision`] with an error bound
/// ([`accuracy`]).  It is accepted when the bound covers the requested
/// digits of every part it shows ([`settle`]); otherwise — catastrophic
/// cancellation, amplification by `exp` or a division by a small
/// difference, or just a pessimistic bound — the whole expression is
/// re-evaluated at a higher precision (Ziv's strategy), up to twice the
/// initial precision plus 256 bits (and the configured maximum), as SymPy's
/// `evalf` retries an `Add` that lost its accuracy.  Before 0.26 the first
/// value was returned whatever its accuracy: `exp(10⁻³⁰) − 1` came out `0`,
/// and a quotient by a difference that is zero to the working precision
/// came out as noise.
///
/// Only the bound certifies digits.  Before 0.30 two successive nonzero
/// values that agreed to the requested digits were accepted too, and
/// agreement is no evidence when an input rounds to the same value at both
/// precisions: `(1 + 10⁻¹⁵⁰)^(10¹⁵⁰)` (truly `e`) was `1` at 16 and 30
/// digits (`1 + 10⁻¹⁵⁰` is 1 at 128 and at 256 bits), and
/// `exp(11/15·10⁻⁴⁰) − (1 + 11/15·10⁻⁴⁰) + I₅₀(1)` lost its first term
/// (`2.7·10⁻⁸¹`, below both precisions) and printed `2.934…·10⁻⁸⁰` for
/// `3.204…·10⁻⁸⁰`.  The nodes that are more accurate than their propagated
/// bound report their own (`sin` of an exact huge rational, reduced from
/// its exact value: see `accuracy::node_error`).
///
/// A value that is zero to the precision reached — its error ball contains
/// 0 and shrank with the precision, or the value itself shrank with every
/// increase in precision — is pursued further, doubling the precision up
/// to the limit of `search` (see [`ZeroSearch`], [`ZERO_SEARCH_BITS`]):
/// a tiny value hidden by cancellation is resolved there.  So is a value
/// whose bound shrinks with the precision without covering the digits yet
/// (`(1 + 10⁻¹⁵⁰)^(10¹⁵⁰)` needs about 560 bits at 16 digits), unless the
/// bound says the digits need more than the limit (refused at once).  At the limit a
/// ball that still contains 0 is returned as 0 ([`Settled::ZeroToPrecision`];
/// SymPy returns a float with no significant digits).  Any other value
/// lacking the digits is refused with [`SymplexError::PrecisionExhausted`]:
/// a value whose magnitude fell with the precision but whose ball excludes
/// 0 (before 0.30 it was 0 too), or an infinite value — from finite inputs
/// it can only come from a division by a difference that cancelled to 0,
/// whose true value is unknown.
///
/// The zero search is not only for the root.  A value without a bound, or
/// without a finite value (NaN, `±∞`), because some node's *arguments* are
/// too imprecise ([`precision_limited`]: a quotient of two differences that
/// are both 0 at the working precision, a function at an argument that
/// cancelled to 0 or onto a pole, the side of a cut decided by a part within
/// its error of 0) is pursued the same way, to the same limit: the
/// arguments' balls shrink with the precision.  Before 0.31 such a value
/// stopped at the cap (NaN at once): `(e^ε − 1)/(e^{2ε} − 1)` at `ε = 10⁻⁴⁵`
/// was refused at 16 digits and `erfc⁻¹(sin(1 + 10⁻¹⁵⁰) − sin 1)` at 16 and
/// 30 digits.  The internal tolerance checks ([`ZeroSearch::Cap`]) are not
/// affected (their search ends at the cap), and an infinite value that no
/// precision cures — beyond the exponent range — fails where it arises
/// ([`exponent_range_error`]).
fn evaluate_adaptive(
    arena: &Arena,
    expr: ExprId,
    digits: u32,
    search: ZeroSearch,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Adaptive, SymplexError> {
    let prec0 = working_precision(digits);
    let max_prec = arena.config.max_evalf_precision as usize;
    let cap = (2 * prec0).max(prec0 + 256).min(max_prec).max(prec0);
    let deep = match search {
        ZeroSearch::Cap => cap,
        ZeroSearch::Deep | ZeroSearch::Number => (prec0 + ZERO_SEARCH_BITS).min(max_prec).max(cap),
    };
    let needed = i64::from(digits) * 3322 / 1000 + 4;
    let post_order = walk::post_order_ids(arena, expr);
    let mut prec = prec0;
    // The previous evaluation: the magnitude of its value and its error
    // bound, both absolute (`log₂`), and its precision.
    let mut previous: Option<(Option<i64>, usize, accuracy::ErrExp)> = None;
    // Pursuits of a zero ball that lost a term (each to a higher precision,
    // within the configured maximum; the count is only a safeguard).
    let mut hidden_pursuits = 0u32;
    loop {
        let Evaluated {
            value,
            bound,
            precision_limited,
            underflowed_nonzero,
            beyond,
            absorbed,
            exact_bits,
            second_bits,
        } = evaluate_once(arena, expr, &post_order, prec, rm, cc)?;
        // The precision that holds every exact value in full, then their
        // second-order parts, for a result read as a number.
        let (inputs, second) = match search {
            ZeroSearch::Number => (
                usize::try_from(exact_bits).unwrap_or(usize::MAX),
                usize::try_from(second_bits).unwrap_or(usize::MAX),
            ),
            ZeroSearch::Cap | ZeroSearch::Deep => (0, 0),
        };
        // A value below the exponent range known scaled is settled as its
        // mantissa, the absolute tests shifted by its scale.
        let (value, bound, scale) = match &beyond {
            Some(s) => (s.m.clone(), s.eb, s.k),
            None => (value, bound, 0),
        };
        let err = bound.joint();
        let below =
            beyond.is_none() && accuracy::mag(&value).is_none() && accuracy::is_underflow(err);
        // A number that is not 0 but lies below the exponent range: no
        // precision brings it back, and 0 is not one of its digits.
        if below && let Some(s) = underflowed_nonzero {
            debug!(prec, err, "evalf: a nonzero value underflowed");
            return Ok(Adaptive::Underflow(s));
        }
        // 0 within the underflow bound, of unknown sign or zeroness: no
        // precision decides it.  Before 0.34 it was a zero to the precision.
        if below {
            debug!(prec, err, "evalf: an underflow of unknown sign");
            return Ok(Adaptive::Undecided);
        }
        let nan = value.0.is_nan() || value.1.is_nan();
        let finite = !(nan || value.0.is_inf() || value.1.is_inf());
        // A value without a bound (or without a finite value) because some
        // node's arguments are too imprecise — not because the root is zero
        // to the working precision — is pursued as such a root is, to the end
        // of the zero search: the arguments' balls shrink with the precision
        // (`precision_limited`).  Before 0.31 it stopped at the cap: `(e^ε −
        // 1)/(e^{2ε} − 1)` at `ε = 10⁻⁴⁵` (`0/0` at 128 bits, NaN) was refused
        // at once at 16 digits, and `erfc⁻¹(sin(1 + 10⁻¹⁵⁰) − sin 1)` (its
        // argument needs about 600 bits) at 16 and 30 digits.
        let limited = precision_limited && (!finite || accuracy::is_unknown(err));
        if nan && !limited {
            return Err(SymplexError::PrecisionExhausted {
                requested: digits,
                achieved: 0,
            });
        }
        if finite && let Some(v) = settle(&value, bound, digits, needed, prec) {
            if let Some(s) = beyond {
                debug!(prec, scale, "evalf: a value below the exponent range");
                return Ok(Adaptive::Beyond(extended::Scaled { m: v, ..s }));
            }
            return Ok(Adaptive::Settled(v, Settled::Certified));
        }
        let lift = |e: accuracy::ErrExp| accuracy::shift(e, scale as f64);
        let acc = accuracy::accurate_bits(&value, err);
        // Only with a bound: `sign` of a value that cancelled to 0 is 0 at
        // every precision, but its true value may be ±1.  And only a ball
        // that shrinks with the precision: a true zero's error falls about
        // a bit per bit gained, while near a pole it grows with the value —
        // `tan(π(1/2 − 10⁻³⁰⁰))` (truly `3.2·10²⁹⁹`) had a ball of `2³⁹⁶`
        // around `10⁴⁰` noise, which contains 0, and came out `0`.
        //
        // And only a value that is itself noise: 0, or falling with the
        // precision as the rounding residue of a cancellation does.  A
        // value that stays put inside a ball that contains 0 has a
        // pessimistic bound, not a zero: `zeta(720·polygamma(1669, E))` is
        // 1 at every precision, its argument (`≈ 10⁴⁰⁰⁰`) is known to its
        // relative error, the bound of `ζ′` was at least 1, so the ball held
        // 0 — and the value was `0` before 0.30.
        let known = finite && !accuracy::is_unknown(err);
        let (ball_shrinking, value_shrinking) = match &previous {
            None => (true, accuracy::mag(&value).is_none()),
            Some((prev_mag, prev_prec, prev_err)) => {
                let gained = i64::try_from(prec - prev_prec).unwrap_or(0);
                // (An underflow's ball is the bottom of the exponent range.)
                let half = (gained / 2) as f64;
                let ball = accuracy::is_exact(err)
                    || accuracy::is_underflow(err)
                    || lift(err) <= *prev_err - half;
                // Against the previous value, or its ball when it was 0.
                let value = match (accuracy::mag(&value).map(|m| m + scale), prev_mag) {
                    (None, _) => true,
                    (Some(m), Some(pm)) => m <= pm - gained / 2,
                    (Some(m), None) => m as f64 <= *prev_err - half,
                };
                (ball, value)
            }
        };
        let noise = known && value_shrinking;
        let zero_ball = noise && ball_shrinking && accuracy::contains_zero(&value, err);
        // A zero ball is returned as 0 only when its radius is below the
        // requested digits in absolute terms, `2^err ≤ 2^−needed`: the 0
        // loses the radius, and only then is it right to those digits
        // whatever the true value.  A wider ball says nothing (it holds
        // numbers of every size up to its radius): the cancellation is
        // deeper than the search so far.  A result read as a number, and
        // the deep tests of the crate ([`ZeroSearch::Number`],
        // [`ZeroSearch::Deep`]), pursue it to the configured maximum
        // precision; the internal tolerance checks ([`ZeroSearch::Cap`]) stop
        // at their cap.  Then it is refused.  Before 0.30 any zero ball at
        // the end of the search was 0: `(i·sin s + cos s)·e^(cos 2x)` with
        // `s = sin 2x` at `x = 1/3 + 4i` (the trigonometric form of
        // `exp(exp(2ix))`, truly `1.000263649 + 0.000207495i`) cancels about
        // 3,400 bits and was `0` with a ball of radius `2²²²⁷` at 1,152 bits.
        let small_zero = zero_ball && lift(err) <= -(needed as f64);
        let wide_zero = zero_ball && !small_zero;
        // Past the cap only a value that is noise, or whose bound falls with
        // the precision (the precision it needs is then predictable), is
        // pursued, to the end of the search — not an underflow: below the
        // exponent range no precision resolves it.  (`(1 + 10⁻¹⁵⁰)^(10¹⁵⁰)`
        // needs about 560 bits at 16 digits, past the cap of 384.)
        let converging = known && ball_shrinking && previous.is_some();
        let pursue = (noise || converging || limited) && !accuracy::is_underflow(err);
        let limit = if wide_zero && search != ZeroSearch::Cap {
            max_prec.max(deep)
        } else if pursue || prec > cap {
            deep
        } else {
            cap
        };
        // A bound that says the digits need more than the search allows is
        // refused now rather than after an evaluation at its limit.
        if let Some(a) = acc
            && known
            && !noise
            && prec < limit
            && prec as f64 + (needed as f64 - a) > deep as f64
        {
            debug!(
                prec,
                err,
                ?acc,
                "evalf: the bound needs more than the search allows"
            );
            return Err(SymplexError::PrecisionExhausted {
                requested: digits,
                achieved: achieved_digits(Some(a), digits),
            });
        }
        // A zero ball that lost a nonzero term below its error is not taken
        // for 0 by a result read as a number: if the rest cancels exactly,
        // the value is that term.  It is pursued to the precision that keeps
        // the nearest such term (its `depth` bits more, and a margin) — and
        // from there, as long as some term is lost — and refused when that
        // is beyond the configured maximum or the term lies below the
        // exponent range.  Before 0.35 it was 0: `sin²1 + cos²1 − 1 +
        // e^(−10¹⁰)`, `sin²1 + cos²1 − 1 + sin(10⁻²⁰⁰⁰)` (`10⁻²⁰⁰⁰`, 6,644
        // bits below the terms, beyond the 1,024-bit search).
        //
        // A zero below the precision that holds the exact inputs in full
        // (`input_bits`) may be the rounding of an input, and a result read
        // as a number pursues it there too: before 0.35 `sin(2/3 + 10⁻⁴⁰⁰)
        // − sin(2/3)` printed `0` (truly `7.86·10⁻⁴⁰¹`).  And from there to
        // the precision of the second-order part of an input with a small
        // part (`second_order_bits`; refused beyond the maximum).
        let margin = usize::try_from(needed).unwrap_or(0) + 32;
        let lost_target = absorbed.and_then(|a| a.nearest).map(|nearest| {
            prec.saturating_add(nearest.ceil() as usize)
                .saturating_add(margin)
        });
        let input_target = if inputs > prec {
            Some(inputs.saturating_add(margin))
        } else {
            (second > prec).then(|| second.saturating_add(margin))
        };
        let lost_below_range = absorbed.is_some_and(|a| a.below_range);
        let hidden = if !small_zero || search == ZeroSearch::Cap {
            None
        } else if lost_below_range {
            Some(None)
        } else {
            lost_target
                .into_iter()
                .chain(input_target)
                .min()
                .map(|target| (target <= max_prec && hidden_pursuits < 16).then_some(target))
        };

        if prec >= limit {
            if small_zero {
                match hidden {
                    None => {
                        debug!(prec, err, "evalf: zero to the working precision");
                        return Ok(Adaptive::Settled(c_zero(prec0), Settled::ZeroToPrecision));
                    }
                    Some(Some(target)) => {
                        debug!(prec, target, "evalf: a zero ball lost a term; pursued");
                        previous = Some((None, prec, lift(err)));
                        prec = target;
                        hidden_pursuits += 1;
                        continue;
                    }
                    Some(None) => {
                        debug!(prec, err, ?absorbed, "evalf: a zero ball lost a term");
                        return Ok(Adaptive::Hidden {
                            below_range: lost_below_range,
                        });
                    }
                }
            }
            debug!(prec, err, ?acc, "evalf: precision exhausted");
            return Err(SymplexError::PrecisionExhausted {
                requested: digits,
                achieved: achieved_digits(acc, digits),
            });
        }
        let step = match acc {
            Some(a) if known => (needed as f64 - a).clamp(0.0, prec as f64).ceil() as usize + 32,
            // A value that is 0 to the working precision says nothing about
            // the precision its first bit needs: go to the cap, and from
            // there double.
            None if known && accuracy::mag(&value).is_none() && prec < cap => cap - prec,
            _ => prec,
        };
        previous = Some((accuracy::mag(&value).map(|m| m + scale), prec, lift(err)));
        prec = (prec + step.max(64)).min(limit);
        // Within a quarter of the limit, the limit: the search for a zero
        // would otherwise end with two evaluations of nearly the same cost
        // (3,072 and 3,200 bits at 16 digits).
        if prec > cap && 4 * (limit - prec) < limit {
            prec = limit;
        }
        debug!(prec, ?acc, "evalf: re-evaluating at a higher precision");
    }
}

/// The decimal digits `acc` accurate bits stand for, at most `digits`.
fn achieved_digits(acc: Option<f64>, digits: u32) -> u32 {
    acc.map_or(0.0, |a| (a.max(0.0) * 0.301).min(f64::from(digits))) as u32
}

/// `value ± bound` as a result certified to `digits` digits (`needed`
/// bits), or `None` when it is not yet.
///
/// The printer shows each part of a complex value with `digits`
/// significant digits of its own unless it is negligible next to the
/// other part ([`is_negligible_part`]), so a part that is shown must carry
/// `needed` bits relative to its own magnitude, not only relative to `|z|`.
/// A part whose error ball contains 0 is below the precision of the result
/// (the joint bound holds) and is set to 0: its digits are noise.  Before
/// 0.30 only the joint accuracy was required, and the smaller part printed
/// uncertified digits: `ln(W(−1/e + 10⁻³⁵))` was `−7.373338…·10⁻¹⁸ + πi`
/// at 16 digits (truly `−7.373306…·10⁻¹⁸`), `Ci(x) + i·(e^(10⁻¹⁶) − 1 −
/// 10⁻¹⁶)` printed an imaginary part `5.00000000000000016666666671757·10⁻³³`
/// at 30 digits (truly `…6666666666667·10⁻³³`).
fn settle(
    value: &Complex,
    bound: accuracy::Bound,
    digits: u32,
    needed: i64,
    prec: usize,
) -> Option<Complex> {
    if accuracy::mag(value).is_none() {
        return bound.is_exact().then(|| value.clone());
    }
    if accuracy::accurate_bits(value, bound.joint())? < needed as f64 {
        return None;
    }
    // `Some(true)`: set the part to 0; `Some(false)`: keep it; `None`: it
    // lacks digits.
    let part = |p: &BigFloat, e: accuracy::ErrExp, other: &BigFloat| -> Option<bool> {
        if accuracy::exact_zero(p, e) {
            return Some(false);
        }
        if accuracy::part_contains_zero(p, e) {
            return Some(true);
        }
        if is_negligible_part(p, other, digits) || accuracy::is_exact(e) {
            return Some(false);
        }
        (accuracy::part_lg_low(p) - e >= needed as f64).then_some(false)
    };
    let zero_re = part(&value.0, bound.re, &value.1)?;
    let zero_im = part(&value.1, bound.im, &value.0)?;
    let mut out = value.clone();
    if zero_re {
        out.0 = BigFloat::new(prec);
    }
    if zero_im {
        out.1 = BigFloat::new(prec);
    }
    Some(out)
}

// ═══════════════════════════════════════════════════════════════════════════
// Direct `f64` / `Complex64` results (no decimal string in between)
// ═══════════════════════════════════════════════════════════════════════════

/// Decimal digits requested by `Ex::eval_f64` and `Ex::eval_complex64`:
/// 16 digits map to a 128-bit working precision (see [`evalf`]), the same
/// precision [`evalf_f64`] and [`evalf_complex64`] evaluate at.
pub(crate) const F64_DIGITS: u32 = 16;

thread_local! {
    /// The constants cache of the `f64` route, kept per thread.
    ///
    /// `Consts::new()` alone costs ~170 µs and a cold cache recomputes π
    /// and `ln 2` on every `sin`/`exp` (`exp(2)` at 128 bits: 475 µs cold,
    /// 2.5 µs warm), which dominated every `eval_f64`.  The route always
    /// evaluates at the same precision, so the cache stays small, and
    /// astro-float rounds each constant correctly to the precision asked
    /// for, so a warm cache returns the same bits a cold one would.
    static F64_CONSTS: std::cell::RefCell<Option<Consts>> = const { std::cell::RefCell::new(None) };
}

/// Run `f` with this thread's constants cache, creating it on first use.
///
/// The cache is taken out of its slot for the duration of `f` and put back
/// afterwards, so a nested evaluation on the same thread (a definite
/// integral's integrand, say) finds the slot empty and simply uses a fresh
/// cache instead of panicking on a double borrow.
fn with_f64_consts<T>(
    f: impl FnOnce(&mut Consts) -> Result<T, SymplexError>,
) -> Result<T, SymplexError> {
    let mut cc = match F64_CONSTS.with(|slot| slot.borrow_mut().take()) {
        Some(cc) => cc,
        None => Consts::new().map_err(|e| {
            SymplexError::NotImplemented(format!("astro-float constants init failed: {e:?}"))
        })?,
    };
    let out = f(&mut cc);
    F64_CONSTS.with(|slot| {
        let mut slot = slot.borrow_mut();
        if slot.is_none() {
            *slot = Some(cc);
        }
    });
    out
}

/// Evaluate `expr` to an arbitrary-precision complex value at the working
/// precision [`evalf`] uses for `digits` decimal digits — the evaluation
/// half of [`evalf`], without the decimal formatting — and how it was
/// settled (`search`: see [`ZeroSearch`]).
///
/// Errors as [`evalf`]: [`SymplexError::PrecisionExhausted`] when the
/// precision exceeds the configured maximum or the result is NaN,
/// [`SymplexError::FreeSymbol`] for an unbound symbol.
fn evalf_value(
    arena: &Arena,
    expr: ExprId,
    digits: u32,
    search: ZeroSearch,
) -> Result<(Complex, Settled), SymplexError> {
    let prec = ((digits as usize) * 34 / 10 + 64).max(128);
    // A number below the exponent range is 0 within its bound, and not
    // known to be 0 by that bound: zero to the precision, for the tolerance
    // checks of the crate and for the `f64` routes, whose correctly rounded
    // value it is.
    evalf_adaptive_value(arena, expr, digits, search).map(|a| match a {
        Adaptive::Settled(z, settled) => (z, settled),
        Adaptive::Underflow(_)
        | Adaptive::Beyond(_)
        | Adaptive::Undecided
        | Adaptive::Hidden { .. } => (c_zero(prec), Settled::ZeroToPrecision),
    })
}

/// [`evaluate_adaptive`] for the callers inside the crate, after the checks
/// of [`evalf`] (the configured maximum precision, free symbols).
fn evalf_adaptive_value(
    arena: &Arena,
    expr: ExprId,
    digits: u32,
    search: ZeroSearch,
) -> Result<Adaptive, SymplexError> {
    let prec = ((digits as usize) * 34 / 10 + 64).max(128);
    let max_prec = arena.config.max_evalf_precision as usize;
    if prec > max_prec {
        return Err(SymplexError::PrecisionExhausted {
            requested: digits,
            achieved: (max_prec * 10 / 34).saturating_sub(6) as u32,
        });
    }

    let free = walk::free_symbols(arena, expr);
    if !free.is_empty() {
        let mut names: Vec<&str> = free
            .iter()
            .filter_map(|&id| match arena.node(id) {
                ExprNode::Symbol(sid) => Some(arena.symbol_name(*sid)),
                _ => None,
            })
            .collect();
        names.sort_unstable();
        if let Some(name) = names.first() {
            debug!(symbol = name, "evalf_value: expression has free symbols");
            return Err(SymplexError::FreeSymbol {
                name: (*name).to_owned(),
            });
        }
    }

    let rm = RoundingMode::ToEven;
    with_f64_consts(|cc| evaluate_adaptive(arena, expr, digits, search, rm, cc))
}

/// [`evalf_value`] for the zero and sign tests of the rest of the crate
/// (`poly::algebraic::is_zero_checked`): the value of the variable-free
/// `expr` to `digits` digits with the [`ZeroSearch`] `search`, and whether
/// it is certified or only zero to the precision reached — a distinction
/// [`evalf_complex`] does not make.
///
/// A number below the exponent range that is certainly not 0 is
/// [`Settled::Certified`] with a stand-in at the bottom of the range that
/// has its sign (its direction, when it is known scaled): its digits are
/// not the value's, its zeroness, sign and realness are.  One of unknown
/// direction, or 0 within the underflow bound and not known to be nonzero,
/// is an error: neither is 0 to a precision the search chose.  Before 0.34
/// both were [`Settled::ZeroToPrecision`], which `solve` (and `polysys`)
/// read as 0: `solve(exp(−10¹⁰), x)` was an identity, every `x` a
/// solution.
///
/// # Errors
///
/// As [`evalf`].
pub(crate) fn evalf_settled(
    arena: &Arena,
    expr: ExprId,
    digits: u32,
    search: ZeroSearch,
) -> Result<(Complex, Settled), SymplexError> {
    let prec = ((digits as usize) * 34 / 10 + 64).max(128);
    match evalf_adaptive_value(arena, expr, digits, search)? {
        Adaptive::Settled(z, settled) => Ok((z, settled)),
        Adaptive::Beyond(s) => s
            .representative(prec)
            .map(|z| (z, Settled::Certified))
            .ok_or_else(underflow_error),
        Adaptive::Underflow(accuracy::Nonzero::Positive) => Ok((
            (extended::tiny(false, prec), BigFloat::new(prec)),
            Settled::Certified,
        )),
        Adaptive::Underflow(accuracy::Nonzero::Negative) => Ok((
            (extended::tiny(true, prec), BigFloat::new(prec)),
            Settled::Certified,
        )),
        Adaptive::Underflow(accuracy::Nonzero::Unsigned) => Err(underflow_error()),
        Adaptive::Undecided => Err(undecided_error()),
        Adaptive::Hidden { below_range: true } => Err(hidden_error()),
        Adaptive::Hidden { below_range: false } => Err(hidden_deep_error(digits)),
    }
}

/// `ln x` for a positive real constant `x`, from a 16-digit evaluation;
/// `None` when `x` has free symbols, does not evaluate, or is not a
/// positive real number.  Accurate far beyond `f64` range (`x = 10⁻⁴⁰⁰`
/// is fine), for callers that need a magnitude estimate.
pub(crate) fn ln_of_positive_constant(arena: &Arena, x: ExprId) -> Option<f64> {
    // A value that is only zero to the precision reached has no logarithm
    // (astro-float's `is_positive` is the sign bit, true for `+0`).  One
    // below the exponent range has, when it is known scaled.
    let z = match evalf_adaptive_value(arena, x, F64_DIGITS, ZeroSearch::Cap).ok()? {
        Adaptive::Settled(z, _) => z,
        Adaptive::Beyond(s) => {
            let real_positive = s.m.1.is_zero() && bf_strictly_positive(&s.m.0);
            return real_positive.then(|| s.ln_abs()).flatten();
        }
        Adaptive::Underflow(_) | Adaptive::Undecided | Adaptive::Hidden { .. } => return None,
    };
    if !bf_strictly_positive(&z.0) || !is_real_to_digits(&z, F64_DIGITS) {
        return None;
    }
    let e = z.0.exponent()?;
    let mut m = z.0.clone();
    m.set_exponent(0); // m ∈ [1/2, 1)
    let m = bigfloat_to_f64_rounded(&m, RoundingMode::ToEven).ok()?;
    Some(m.ln() + f64::from(e) * std::f64::consts::LN_2)
}

/// [`evalf_value`] for the rest of the crate: the variable-free `expr`
/// evaluated to `digits` correct significant digits, as an
/// arbitrary-precision complex value.  An `Ok` value is finite.  A value
/// that is zero to the precision is pursued only to the cap of the digits
/// ([`ZeroSearch::Cap`]): the callers compare against a tolerance and meet
/// true zeros all the time (the integrator's `F′ − f`).
///
/// # Errors
///
/// As [`evalf`].
pub(crate) fn evalf_complex(
    arena: &Arena,
    expr: ExprId,
    digits: u32,
) -> Result<Complex, SymplexError> {
    evalf_value(arena, expr, digits, ZeroSearch::Cap).map(|(z, _)| z)
}

/// `|z|` rounded to an `f64`: `+∞` beyond the `f64` range, `0.0` below it;
/// `None` for NaN.
pub(crate) fn abs_to_f64(z: &Complex) -> Option<f64> {
    let rm = RoundingMode::ToEven;
    bigfloat_to_f64_rounded(&crate::base::bigcomplex::c_abs(z, 128, rm), rm).ok()
}

/// `|a − b|` rounded to an `f64` (see [`abs_to_f64`]), the difference taken
/// exactly enough that two values agreeing to their last digit give a
/// difference at that digit, not 0 or noise from a coarser rounding.
pub(crate) fn distance_to_f64(a: &Complex, b: &Complex) -> Option<f64> {
    let prec = [&a.0, &a.1, &b.0, &b.1]
        .iter()
        .filter_map(|x| x.mantissa_max_bit_len())
        .max()
        .unwrap_or(128)
        .max(128)
        + 64;
    abs_to_f64(&crate::base::bigcomplex::c_sub(
        a,
        b,
        prec,
        RoundingMode::ToEven,
    ))
}

/// Is `z` real to `digits` digits — its imaginary part zero or negligible
/// next to its real part, the criterion by which [`evalf`] prints a real
/// number?
pub(crate) fn is_real_to_digits(z: &Complex, digits: u32) -> bool {
    is_negligible_part(&z.1, &z.0, digits)
}

/// One part of a complex result as an `f64`: `0.0` when it is negligible
/// next to the other part (the criterion `format_complex` uses to print a
/// real or a pure-imaginary number), otherwise the correctly rounded
/// value; an infinite part is refused, as the decimal route refuses to
/// parse `oo`.
fn finite_part_to_f64(part: &BigFloat, other: &BigFloat, digits: u32) -> Result<f64, SymplexError> {
    if is_negligible_part(part, other, digits) {
        return Ok(0.0);
    }
    if part.is_inf() {
        return Err(SymplexError::Unevaluable {
            reason: "the value overflowed the arbitrary-precision exponent range".into(),
        });
    }
    bigfloat_to_f64_rounded(part, RoundingMode::ToEven)
}

/// Evaluate `expr` to a [`Complex64`] at the precision behind
/// `Ex::eval_complex64` (16 digits, 128 working bits), rounding each part
/// straight from the `BigFloat` result — the string-free counterpart of
/// `evalf(arena, expr, 16)` followed by a parse.  A part that is
/// negligible next to the other (below the printed precision) is `0.0`,
/// exactly as it would be absent from the printed number.
///
/// The direct rounding is correct to the last bit; the decimal route
/// rounded to 16 significant digits first, which can land one ulp away.
///
/// An expression containing a definite integral is served when the `f64`
/// quadrature certifies [`QUADRATURE_F64_DIGITS`] digits (it seldom
/// certifies 16); the `f64` returned is then the quadrature's estimate.
///
/// # Errors
///
/// As [`evalf`]; additionally [`SymplexError::Unevaluable`] when a part is
/// infinite.
pub(crate) fn evalf_complex64(arena: &Arena, expr: ExprId) -> Result<Complex64, SymplexError> {
    let digits = if contains_definite_integral(arena, expr) {
        QUADRATURE_F64_DIGITS
    } else {
        F64_DIGITS
    };
    let (z, _) = evalf_value(arena, expr, digits, ZeroSearch::Number)?;
    let re = finite_part_to_f64(&z.0, &z.1, digits)?;
    let im = finite_part_to_f64(&z.1, &z.0, digits)?;
    Ok(Complex64::new(re, im))
}

/// Evaluate `expr` to an `f64` at the precision behind `Ex::eval_f64`
/// (see [`evalf_complex64`]): the real value `evalf(expr, 16)` prints.
///
/// # Errors
///
/// As [`evalf_complex64`]; [`SymplexError::ComputationFailed`] when the
/// value is not real to the digits evaluated — its imaginary part is not
/// negligible next to its real part (the criterion by which [`evalf`]
/// prints a real number), however small it is.  Before 0.30 an imaginary
/// part up to `1e-15` in absolute value was dropped: `sqrt(−10⁻⁴⁰)`
/// (`10⁻²⁰·i`) was `0.0`, and `ln(1 + 6·10⁻¹⁶)·(1 + 2·10⁻¹²·i)` lost
/// an imaginary part of `2·10⁻¹²` of its value.
pub(crate) fn evalf_f64(arena: &Arena, expr: ExprId) -> Result<f64, SymplexError> {
    let digits = if contains_definite_integral(arena, expr) {
        QUADRATURE_F64_DIGITS
    } else {
        F64_DIGITS
    };
    let (z, _) = evalf_value(arena, expr, digits, ZeroSearch::Number)?;
    if !is_negligible_part(&z.1, &z.0, digits) {
        let im = bigfloat_to_f64_rounded(&z.1, RoundingMode::ToEven).unwrap_or(f64::NAN);
        return Err(SymplexError::ComputationFailed {
            operation: "eval_f64",
            reason: format!(
                "expression has nonzero imaginary part (im={im}); use eval_complex64() for complex results"
            ),
        });
    }
    finite_part_to_f64(&z.0, &z.1, digits)
}

/// Evaluate a constant (variable-free) arena expression to `f64`.
///
/// Returns `None` if the expression contains free symbols, produces
/// a complex result, or evaluation fails for any reason.
///
/// The expression is first simplified via [`eval`](crate::transforms::eval::eval)
/// to reduce exact values (e.g., `sin(π) → 0`, `Γ(5) → 24`) before
/// numerical evaluation.
pub(crate) fn eval_const_f64(arena: &mut Arena, expr: ExprId) -> Option<f64> {
    // Simplify exact values first.
    let evaled = crate::transforms::eval::eval(arena, expr);

    // Fast path: if the result is already a rational number, convert directly
    // without invoking the expensive arbitrary-precision machinery.
    if let Some(r) = arena.as_num(evaled) {
        let result = crate::base::numeric::ratio_to_f64(r)?;
        tracing::trace!(result, "eval_const_f64: rational fast path");
        return Some(result);
    }

    // Fall back to arbitrary-precision evaluation to 16 decimal digits,
    // then parse the resulting string.  The `evalf` call takes `&Arena`
    // (immutable), which Rust allows via automatic reborrowing of our
    // `&mut Arena`.
    match evalf_with(arena, evaled, 16, ZeroSearch::Cap, Underflow::Zero) {
        Ok(s) => {
            let result = s.parse::<f64>().ok();
            tracing::trace!(?result, decimal_str = %s, "eval_const_f64: evalf path");
            result
        }
        Err(e) => {
            tracing::debug!(?e, "eval_const_f64: evalf failed");
            None
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Node evaluation
// ═══════════════════════════════════════════════════════════════════════════

/// Evaluate a single node given its children's values in the cache.
fn eval_node(
    arena: &Arena,
    id: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    let node = arena.node(id);

    match node {
        // ── Atoms ──────────────────────────────────────────────────
        ExprNode::Num(nid) => {
            let r = arena.num(*nid);
            Ok((ratio_to_bigfloat(r, prec, rm), BigFloat::new(prec)))
        }

        ExprNode::Pi => Ok((cc.pi(prec, rm).clone(), BigFloat::new(prec))),

        ExprNode::E => Ok((cc.e(prec, rm).clone(), BigFloat::new(prec))),

        ExprNode::ImaginaryUnit => Ok((BigFloat::new(prec), BigFloat::from_i32(1, prec))),

        // ── Named constants (arbitrary precision) ───────────────────────────
        ExprNode::EulerGamma => {
            debug!(prec, "evalf: EulerGamma via Brent–McMillan");
            let g = arb_euler_gamma(prec, rm, cc)?;
            Ok((g, BigFloat::new(prec)))
        }
        ExprNode::Catalan => {
            debug!(prec, "evalf: Catalan via Ramanujan series");
            let g = arb_catalan(prec, rm, cc)?;
            Ok((g, BigFloat::new(prec)))
        }
        ExprNode::GoldenRatio => {
            // φ = (1 + √5)/2, exactly via a single square root.
            let wp = prec + 16;
            let five = BigFloat::from_i32(5, wp);
            let sqrt5 = five.sqrt(wp, rm);
            let one = BigFloat::from_i32(1, wp);
            let two = BigFloat::from_i32(2, wp);
            let phi = one.add(&sqrt5, wp, rm).div(&two, prec, rm);
            Ok((phi, BigFloat::new(prec)))
        }

        // ── Complex analysis ────────────────────────────────────────────
        ExprNode::Re(inner) => {
            let val = get_cached(cache, *inner)?;
            Ok((val.0.clone(), BigFloat::new(prec)))
        }
        ExprNode::Im(inner) => {
            let val = get_cached(cache, *inner)?;
            Ok((val.1.clone(), BigFloat::new(prec)))
        }
        ExprNode::Conjugate(inner) => {
            let val = get_cached(cache, *inner)?;
            Ok((val.0.clone(), val.1.neg()))
        }
        ExprNode::Arg(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.0.is_zero() && val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "arg(0) is undefined".into(),
                });
            }
            Ok((atan2_bf(&val.1, &val.0, prec, rm, cc), BigFloat::new(prec)))
        }

        // ── Special functions (0.2) ──────────────────────────────────────
        ExprNode::Si(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Si of complex argument not yet supported in evalf".into(),
                });
            }
            debug!(prec, "evalf: Si via series/asymptotic");
            let (si, _ci) = arb_si_ci(&val.0, true, prec, rm, cc)?;
            Ok((si, BigFloat::new(prec)))
        }
        ExprNode::Ci(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Ci of complex argument not yet supported in evalf".into(),
                });
            }
            if val.0.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Ci(0) is zoo".into(),
                });
            }
            debug!(prec, "evalf: Ci via series/asymptotic");
            let x_abs = val.0.abs();
            let (_si, ci) = arb_si_ci(&x_abs, false, prec, rm, cc)?;
            if val.0.is_negative() {
                // Ci(-x) = Ci(x) + iπ (principal branch of the logarithm).
                Ok((ci, cc.pi(prec, rm).clone()))
            } else {
                Ok((ci, BigFloat::new(prec)))
            }
        }
        ExprNode::Ei(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Ei of complex argument not yet supported in evalf".into(),
                });
            }
            if val.0.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Ei(0) is -∞".into(),
                });
            }
            debug!(prec, "evalf: Ei via series/asymptotic");
            let r = arb_ei(&val.0, prec, rm, cc)?;
            Ok((r, BigFloat::new(prec)))
        }
        ExprNode::Li(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() || val.0.is_negative() {
                return Err(SymplexError::Unevaluable {
                    reason: "li of complex or negative argument not yet supported in evalf".into(),
                });
            }
            if val.0.is_zero() {
                return Ok(c_zero(prec));
            }
            let wp = prec + 32;
            let ln_x = val.0.ln(wp, rm, cc);
            if ln_x.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "li(1) is -∞".into(),
                });
            }
            debug!(prec, "evalf: li via Ei(ln x)");
            let r = arb_ei(&ln_x, prec, rm, cc)?;
            Ok((r, BigFloat::new(prec)))
        }
        ExprNode::Zeta(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "zeta of complex argument not yet supported in evalf".into(),
                });
            }
            debug!(prec, "evalf: zeta via Borwein / functional equation");
            let r = arb_zeta(&val.0, prec, rm, cc)?;
            Ok((r, BigFloat::new(prec)))
        }
        ExprNode::Polygamma(n_id, x_id) => {
            let n_val = get_cached(cache, *n_id)?;
            let x_val = get_cached(cache, *x_id)?;
            if !n_val.1.is_zero() || !x_val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "polygamma of complex arguments not yet supported in evalf".into(),
                });
            }
            let n_f = bigfloat_to_f64(&n_val.0, rm, cc)?;
            let n_round = n_f.round();
            if (n_f - n_round).abs() > 1e-12 || n_round < 0.0 {
                return Err(SymplexError::Unevaluable {
                    reason: "polygamma order must be a non-negative integer".into(),
                });
            }
            // A large order: `(−1)^{n+1}·n!·ζ(n + 1, x)` in log space (before
            // 0.30 refused beyond 10⁴, "order must be a non-negative integer",
            // although `eval` leaves `polygamma(10⁵, 1/2)` symbolic).
            if n_round > 10_000.0 {
                debug!(
                    prec,
                    n = n_round,
                    "evalf: polygamma of large order via Hurwitz zeta"
                );
                let n_exact = BigFloat::from_f64(n_round, 64);
                let r = factorials::polygamma_large(&n_exact, &x_val.0, prec, rm, cc)?;
                return Ok((r, BigFloat::new(prec)));
            }
            let n = n_round as u32;
            if n == 0 {
                let r = arb_digamma(&x_val.0, prec, rm, cc)?;
                return Ok((r, BigFloat::new(prec)));
            }
            debug!(
                prec,
                n, "evalf: polygamma via recurrence + asymptotic series"
            );
            let r = arb_polygamma(n, &x_val.0, prec, rm, cc)?;
            Ok((r, BigFloat::new(prec)))
        }
        ExprNode::KroneckerDelta(i_id, j_id) => {
            let iv = get_cached(cache, *i_id)?;
            let jv = get_cached(cache, *j_id)?;
            let d_re = iv.0.sub(&jv.0, prec, rm);
            let d_im = iv.1.sub(&jv.1, prec, rm);
            if d_re.is_zero() && d_im.is_zero() {
                Ok(c_one(prec))
            } else {
                Ok(c_zero(prec))
            }
        }

        // Evaluated with their own error bounds by `eval_node_with_error`,
        // which never hands them here; without the children's bounds a
        // `Piecewise` decision is never certain.
        ExprNode::PhysicalConstant(..)
        | ExprNode::Sum(..)
        | ExprNode::Product_(..)
        | ExprNode::Piecewise(_)
        | ExprNode::RootOf(..)
        | ExprNode::RootSum(..)
        | ExprNode::DefiniteIntegral(..) => {
            eval_node_with_error(arena, id, cache, &ErrMap::default(), prec, rm, cc).map(|(v, _)| v)
        }

        ExprNode::Infinity | ExprNode::NegInfinity | ExprNode::ComplexInfinity => {
            Err(SymplexError::Unevaluable {
                reason: "cannot evaluate infinity to finite precision".into(),
            })
        }

        // x! = Γ(x + 1) for every real x off the poles (x = −1, −2, …);
        // `eval()` already reduces non-negative integer literals exactly.
        ExprNode::Factorial(x_id) => {
            let x_val = get_cached(cache, *x_id)?;
            if !x_val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "factorial of a complex argument not yet supported in evalf".into(),
                });
            }
            debug!(
                prec,
                "evalf: factorial via arbitrary-precision Gamma(x + 1)"
            );
            let x_plus_1 = x_val
                .0
                .add(&BigFloat::from_i32(1, 64), exact_bits(&x_val.0, prec), rm);
            let r = arb_gamma_real(&x_plus_1, prec, rm, cc)?;
            Ok((r, BigFloat::new(prec)))
        }

        ExprNode::Binomial(n_id, k_id) => {
            debug!(prec, "evalf: Binomial via arbitrary-precision Gamma");
            let n_val = get_cached(cache, *n_id)?;
            let k_val = get_cached(cache, *k_id)?;
            if !n_val.1.is_zero() || !k_val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Binomial of complex arguments not yet supported in evalf".into(),
                });
            }
            // Integer `0 ≤ n < k`: C(n, k) = 0 (the Γ formula below would
            // hit the pole of Γ(n − k + 1)).  Integers exactly: before 0.29
            // `n` within 10⁻¹² of one counted, and `binomial(2 + 10⁻¹³, 3)`
            // was 0 (truly 3.3·10⁻¹⁴).
            if n_val.0.is_int() && k_val.0.is_int() && !n_val.0.is_negative() && k_val.0 > n_val.0 {
                return Ok((BigFloat::new(prec), BigFloat::new(prec)));
            }
            // Where the Γ formula meets a pole, its limit (mpmath's
            // `gammaprod`): before 0.30 `binomial(−7, 2500)` was refused,
            // "Gamma at non-positive integer pole", although it is
            // `C(2506, 6)`.
            if factorials::binomial_meets_pole(&n_val.0, &k_val.0, prec, rm) {
                let r = factorials::binomial(&n_val.0, &k_val.0, prec, rm, cc)?;
                return Ok((r, BigFloat::new(prec)));
            }
            // C(n, k) = Gamma(n+1) / (Gamma(k+1) * Gamma(n-k+1)), the shifted
            // arguments exact.
            let one_bf = BigFloat::from_i32(1, 64);
            let p = exact_bits(&n_val.0, prec).max(exact_bits(&k_val.0, prec)) + 64;
            let n_plus_1 = n_val.0.add(&one_bf, p, rm);
            let k_plus_1 = k_val.0.add(&one_bf, p, rm);
            let n_minus_k = n_val.0.sub(&k_val.0, p, rm);
            let n_minus_k_plus_1 = n_minus_k.add(&one_bf, p, rm);

            let g_numer = arb_gamma_real(&n_plus_1, prec, rm, cc)?;
            let g_k = arb_gamma_real(&k_plus_1, prec, rm, cc)?;
            let g_nmk = arb_gamma_real(&n_minus_k_plus_1, prec, rm, cc)?;
            let g_denom = g_k.mul(&g_nmk, prec, rm);
            if g_denom.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Binomial denominator is zero (pole in Gamma)".into(),
                });
            }
            let result = g_numer.div(&g_denom, prec, rm);
            // `Γ(n + 1)` and `Γ(n − k + 1)` beyond the exponent range for a
            // huge `n` (their quotient NaN, and before 0.31
            // `lambertw(binomial(10⁵⁰, 2), −1)` was refused): for a small
            // integer `k ≥ 0`, `n(n − 1)⋯(n − k + 1)/k!` instead.
            if (result.is_nan() || result.is_inf())
                && (k_val.0.is_zero() || k_val.0.is_int())
                && !k_val.0.is_negative()
                && let Some(k) = bigfloat_to_f64_rounded(&k_val.0, rm)
                    .ok()
                    .filter(|k| *k <= 64.0)
            {
                let k = k as i32;
                let wp = prec + 16;
                let mut product = BigFloat::from_i32(1, wp);
                for j in 0..k {
                    let factor = n_val.0.sub(&BigFloat::from_i32(j, 64), p, rm);
                    product = product.mul(&factor, wp, rm);
                }
                let k_factorial = (1..=k).fold(BigFloat::from_i32(1, wp), |acc, j| {
                    acc.mul(&BigFloat::from_i32(j, 64), wp, rm)
                });
                return Ok((product.div(&k_factorial, prec, rm), BigFloat::new(prec)));
            }
            Ok((result, BigFloat::new(prec)))
        }

        ExprNode::Gamma(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Gamma of complex argument not yet supported in evalf".into(),
                });
            }
            debug!(prec, "evalf: Gamma via Stirling series");
            let result = arb_gamma_real(&val.0, prec, rm, cc)?;
            Ok((result, BigFloat::new(prec)))
        }

        // The analytic continuation of ln Γ (SymPy's `loggamma`): off the
        // real axis by `loggamma`, on it by `arb_log_gamma` (real for
        // x > 0, `ln|Γ(x)| − iπ⌈−x⌉` on the cut).  Before 0.30 a complex
        // argument was refused and the value left of 0 was `ln|Γ(x)|`.
        ExprNode::LogGamma(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                debug!(prec, "evalf: LogGamma of a complex argument");
                return loggamma::loggamma_complex(val, prec, rm, cc);
            }
            debug!(prec, "evalf: LogGamma via Stirling series");
            arb_log_gamma(&val.0, prec, rm, cc)
        }

        ExprNode::Digamma(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Digamma of complex argument not yet supported in evalf".into(),
                });
            }
            let result = arb_digamma(&val.0, prec, rm, cc)?;
            Ok((result, BigFloat::new(prec)))
        }

        ExprNode::Erf(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "erf of complex argument not yet supported in evalf".into(),
                });
            }
            debug!(prec, "evalf: erf via arbitrary-precision series");
            let result = arb_erf(&val.0, prec, rm, cc)?;
            Ok((result, BigFloat::new(prec)))
        }

        ExprNode::Erfc(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "erfc of complex argument not yet supported in evalf".into(),
                });
            }
            debug!(prec, "evalf: erfc via arbitrary-precision series");
            let result = arb_erfc(&val.0, prec, rm, cc)?;
            Ok((result, BigFloat::new(prec)))
        }

        ExprNode::LambertW(_) => eval_lambertw_node(arena, node, cache, prec, rm, cc),

        ExprNode::Beta(a_id, b_id) => {
            let a_val = get_cached(cache, *a_id)?;
            let b_val = get_cached(cache, *b_id)?;
            if !a_val.1.is_zero() || !b_val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Beta of complex arguments not yet supported in evalf".into(),
                });
            }
            // Beta(a,b) = Gamma(a)*Gamma(b)/Gamma(a+b) at arbitrary precision.
            debug!(prec, "evalf: Beta via arbitrary-precision Gamma");
            let ga = arb_gamma_real(&a_val.0, prec, rm, cc)?;
            let gb = arb_gamma_real(&b_val.0, prec, rm, cc)?;
            let p = exact_bits(&a_val.0, prec).max(exact_bits(&b_val.0, prec)) + 64;
            let a_plus_b = a_val.0.add(&b_val.0, p, rm);
            let gab = arb_gamma_real(&a_plus_b, prec, rm, cc)?;
            if gab.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Beta function: Gamma(a+b) is zero".into(),
                });
            }
            let numer = ga.mul(&gb, prec, rm);
            let result = numer.div(&gab, prec, rm);
            Ok((result, BigFloat::new(prec)))
        }

        ExprNode::NaN => Err(SymplexError::Unevaluable {
            reason: "cannot evaluate NaN".into(),
        }),

        ExprNode::Symbol(sid) => {
            let name = arena.symbol_name(*sid);
            Err(SymplexError::FreeSymbol {
                name: name.to_owned(),
            })
        }

        // ── Add ────────────────────────────────────────────────────
        ExprNode::Add(children) => {
            let mut sum = c_zero(prec);
            for &child in children.iter() {
                let val = get_cached(cache, child)?;
                sum = c_add(&sum, val, prec, rm);
            }
            Ok(sum)
        }

        // ── Mul ────────────────────────────────────────────────────
        ExprNode::Mul(children) => {
            let mut product = c_one(prec);
            for &child in children.iter() {
                let val = get_cached(cache, child)?;
                product = c_mul(&product, val, prec, rm);
            }
            Ok(product)
        }

        // ── Pow ────────────────────────────────────────────────────
        ExprNode::Pow(base, exp) => {
            let b = get_cached(cache, *base)?;
            let e = get_cached(cache, *exp)?;

            let b_is_real = b.1.is_zero();
            let e_is_real = e.1.is_zero();

            // Optimization: use sqrt for x^(1/2) with non-negative real base.
            if b_is_real
                && !b.0.is_negative()
                && let ExprNode::Num(nid) = arena.node(*exp)
            {
                let r = arena.num(*nid);
                if *r == Ratio::new(BigInt::from(1), BigInt::from(2)) {
                    return Ok((b.0.sqrt(prec, rm), BigFloat::new(prec)));
                }
            }

            // Optimization: small integer exponents.
            if let Some(n) = try_as_small_int(arena, *exp) {
                if b_is_real {
                    // Real base with integer exponent: use real powi.
                    if n >= 0 {
                        return Ok((b.0.powi(n as usize, prec, rm), BigFloat::new(prec)));
                    } else {
                        let pow_pos = b.0.powi((-n) as usize, prec, rm);
                        let one_bf = BigFloat::from_i32(1, prec);
                        return Ok((one_bf.div(&pow_pos, prec, rm), BigFloat::new(prec)));
                    }
                } else {
                    // Complex base with integer exponent: use c_powi.
                    if n >= 0 {
                        return Ok(c_powi(b, n as usize, prec, rm));
                    } else {
                        let pow_pos = c_powi(b, (-n) as usize, prec, rm);
                        let one_c = c_one(prec);
                        return Ok(c_div(&one_c, &pow_pos, prec, rm));
                    }
                }
            }

            // 0^e: 0 for a real e > 0, infinite for a real e < 0, no value
            // for a non-real e (SymPy's `0**I`, mpmath's `mpc(0)**mpc(1,1)`:
            // nan), as `canon_pow` folds it.  Before 0.30 `0^i` and
            // `0^(−1 + i)` printed `0` (and `0^π` was refused).
            if b.0.is_zero() && b.1.is_zero() && !(e.0.is_zero() && e.1.is_zero()) {
                if e.1.is_zero() && !e.0.is_zero() && e.0.is_positive() {
                    return Ok(c_zero(prec));
                }
                return Err(SymplexError::Unevaluable {
                    reason: if e.1.is_zero() {
                        "cannot evaluate infinity to finite precision".into()
                    } else {
                        "0 to a non-real power has no value".into()
                    },
                });
            }

            // Real positive base with real exponent: exp(e·ln b).
            // (`BigFloat::pow` is avoided — it hangs on exactly
            // representable results such as 4^(1/2); see `bf_pow`.)
            if b_is_real && e_is_real && b.0.is_positive() {
                return Ok((bf_pow(&b.0, &e.0, prec, rm, cc), BigFloat::new(prec)));
            }

            // Negative real base, half-integer exponent n/2:
            // (−r)^(n/2) = r^(n/2)·iⁿ exactly (n odd, so ±i).  Through
            // exp(½·(ln r + iπ)) the real part is r^(n/2)·cos(nπ/2), a rounding
            // residue whose sign then picks the side of the next branch cut.
            if b_is_real
                && b.0.is_negative()
                && let ExprNode::Num(nid) = arena.node(*exp)
                && *arena.num(*nid).denom() == BigInt::from(2)
            {
                let n = arena.num(*nid).numer();
                let r = b.0.abs();
                let magnitude = bf_pow(&r, &e.0, prec, rm, cc);
                let i_power_is_plus_i =
                    num_integer::Integer::mod_floor(n, &BigInt::from(4)) == BigInt::from(1);
                let im = if i_power_is_plus_i {
                    magnitude
                } else {
                    magnitude.neg()
                };
                return Ok((BigFloat::new(prec), im));
            }

            // General complex power: b^e = exp(e * ln(b)), with the angle
            // `Im(e·ln b)` checked as `exp` checks its argument's: reducing
            // a huge inexact angle mod 2π needs π to as many bits, and
            // `(−2)^(−exp(10⁶))` (angle `≈ 10⁴³⁴²⁹⁴`) never finished.
            if (b.0.is_zero() && b.1.is_zero()) || (e.0.is_zero() && e.1.is_zero()) {
                return Ok(c_pow(b, e, prec, rm, cc));
            }
            let product = c_mul(e, &c_ln(b, prec, rm, cc), prec, rm);
            check_trig_arg(&product.1, 0, prec, arena)?;
            Ok(c_exp(&product, prec, rm, cc))
        }

        // ── Neg ────────────────────────────────────────────────────
        ExprNode::Neg(inner) => {
            let val = get_cached(cache, *inner)?;
            Ok(c_neg(val))
        }

        // ── Trig ───────────────────────────────────────────────────
        ExprNode::Sin(inner) => {
            let val = get_cached(cache, *inner)?;
            let (arg, extra) = trig_arg(arena, *inner, val, prec, rm);
            check_trig_arg(&arg, extra, prec, arena)?;
            if val.1.is_zero() {
                Ok((arg.sin(prec, rm, cc), BigFloat::new(prec)))
            } else {
                Ok(c_sin(val, prec, rm, cc))
            }
        }

        ExprNode::Cos(inner) => {
            let val = get_cached(cache, *inner)?;
            let (arg, extra) = trig_arg(arena, *inner, val, prec, rm);
            check_trig_arg(&arg, extra, prec, arena)?;
            if val.1.is_zero() {
                Ok((arg.cos(prec, rm, cc), BigFloat::new(prec)))
            } else {
                Ok(c_cos(val, prec, rm, cc))
            }
        }

        ExprNode::Tan(inner) => {
            let val = get_cached(cache, *inner)?;
            let (arg, extra) = trig_arg(arena, *inner, val, prec, rm);
            check_trig_arg(&arg, extra, prec, arena)?;
            if val.1.is_zero() {
                Ok((arg.tan(prec, rm, cc), BigFloat::new(prec)))
            } else {
                let s = c_sin(val, prec, rm, cc);
                let c = c_cos(val, prec, rm, cc);
                Ok(c_div(&s, &c, prec, rm))
            }
        }

        // ── Exp / Ln ───────────────────────────────────────────────
        ExprNode::Exp(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.exp(prec, rm, cc), BigFloat::new(prec)))
            } else {
                check_trig_arg(&val.1, 0, prec, arena)?;
                Ok(c_exp(val, prec, rm, cc))
            }
        }

        ExprNode::Ln(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() && val.0.is_positive() {
                Ok((val.0.ln(prec, rm, cc), BigFloat::new(prec)))
            } else {
                Ok(c_ln(val, prec, rm, cc))
            }
        }

        // ── Abs ────────────────────────────────────────────────────
        ExprNode::Abs(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.abs(), BigFloat::new(prec)))
            } else {
                Ok((c_abs(val, prec, rm), BigFloat::new(prec)))
            }
        }

        // ── Inverse trig ──────────────────────────────────────────
        // A real argument outside the real domain (`asin 2`, `acosh ½`,
        // `atanh 2`) takes the complex formula, which is the principal value
        // (mpmath's, and so SymPy's `N`); the real routines would give NaN.
        ExprNode::Asin(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                if abs_le_one(&val.0, prec) {
                    return Ok((val.0.asin(prec, rm, cc), BigFloat::new(prec)));
                }
                // |x| > 1: sign(x)·π/2 − i·sign(x)·acosh|x|.
                let half_pi = half_pi_bf(prec, rm, cc);
                let ach = val.0.abs().acosh(prec, rm, cc);
                return Ok(if val.0.is_negative() {
                    (half_pi.neg(), ach)
                } else {
                    (half_pi, ach.neg())
                });
            }
            Ok(c_asin(val, prec, rm, cc))
        }

        ExprNode::Acos(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                if abs_le_one(&val.0, prec) {
                    return Ok((val.0.acos(prec, rm, cc), BigFloat::new(prec)));
                }
                // x > 1: i·acosh x;  x < −1: π − i·acosh|x|.
                let ach = val.0.abs().acosh(prec, rm, cc);
                return Ok(if val.0.is_negative() {
                    (cc.pi(prec, rm).clone(), ach.neg())
                } else {
                    (BigFloat::new(prec), ach)
                });
            }
            Ok(c_acos(val, prec, rm, cc))
        }

        ExprNode::Atan(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.atan(prec, rm, cc), BigFloat::new(prec)))
            } else {
                Ok(c_atan(val, prec, rm, cc))
            }
        }

        // ── Atan2 ─────────────────────────────────────────────────
        ExprNode::Atan2(y_id, x_id) => {
            let yv = get_cached(cache, *y_id)?;
            let xv = get_cached(cache, *x_id)?;
            // Both args must be real for a real atan2 result.
            if yv.1.is_zero() && xv.1.is_zero() {
                Ok((atan2_bf(&yv.0, &xv.0, prec, rm, cc), BigFloat::new(prec)))
            } else {
                // Complex fallback: atan2 is not standard for complex args;
                // compute as -i * ln((x + iy) / sqrt(x² + y²))
                // but for now just use the real parts as a best-effort.
                Err(SymplexError::Unevaluable {
                    reason: "atan2 with complex arguments is not supported".into(),
                })
            }
        }

        // ── Hyperbolic ────────────────────────────────────────────
        ExprNode::Sinh(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.sinh(prec, rm, cc), BigFloat::new(prec)))
            } else {
                check_trig_arg(&val.1, 0, prec, arena)?;
                Ok(c_sinh(val, prec, rm, cc))
            }
        }

        ExprNode::Cosh(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.cosh(prec, rm, cc), BigFloat::new(prec)))
            } else {
                check_trig_arg(&val.1, 0, prec, arena)?;
                Ok(c_cosh(val, prec, rm, cc))
            }
        }

        ExprNode::Tanh(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.tanh(prec, rm, cc), BigFloat::new(prec)))
            } else {
                check_trig_arg(&val.1, 0, prec, arena)?;
                let s = c_sinh(val, prec, rm, cc);
                let c = c_cosh(val, prec, rm, cc);
                Ok(c_div(&s, &c, prec, rm))
            }
        }

        // ── Inverse hyperbolic ────────────────────────────────────
        ExprNode::Asinh(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                Ok((val.0.asinh(prec, rm, cc), BigFloat::new(prec)))
            } else {
                Ok(c_asinh(val, prec, rm, cc))
            }
        }

        ExprNode::Acosh(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                let one = BigFloat::from_i32(1, prec);
                if val.0 >= one {
                    return Ok((val.0.acosh(prec, rm, cc), BigFloat::new(prec)));
                }
                // −1 ≤ x < 1: i·acos x;  x < −1: acosh|x| + iπ.
                return Ok(if val.0 >= one.neg() {
                    (BigFloat::new(prec), val.0.acos(prec, rm, cc))
                } else {
                    (val.0.abs().acosh(prec, rm, cc), cc.pi(prec, rm).clone())
                });
            }
            Ok(c_acosh(val, prec, rm, cc))
        }

        ExprNode::Atanh(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                if abs_le_one(&val.0, prec) {
                    return Ok((val.0.atanh(prec, rm, cc), BigFloat::new(prec)));
                }
                // |x| > 1: atanh(1/x) − sign(x)·iπ/2.
                let recip = BigFloat::from_i32(1, prec).div(&val.0, prec, rm);
                let half_pi = half_pi_bf(prec, rm, cc);
                let im = if val.0.is_negative() {
                    half_pi
                } else {
                    half_pi.neg()
                };
                return Ok((recip.atanh(prec, rm, cc), im));
            }
            Ok(c_atanh(val, prec, rm, cc))
        }

        // ── Sign ───────────────────────────────────────────────────
        ExprNode::Sign(inner) => {
            let val = get_cached(cache, *inner)?;
            if val.1.is_zero() {
                // Real case: sign returns -1, 0, or 1
                if val.0.is_zero() {
                    Ok(c_zero(prec))
                } else if val.0.is_negative() {
                    Ok((BigFloat::from_i32(-1, prec), BigFloat::new(prec)))
                } else {
                    Ok((BigFloat::from_i32(1, prec), BigFloat::new(prec)))
                }
            } else {
                // Complex case: sign(z) = z / |z|
                let modulus = c_abs(val, prec, rm);
                if modulus.is_zero() {
                    Ok(c_zero(prec))
                } else {
                    let denom = (modulus, BigFloat::new(prec));
                    Ok(c_div(val, &denom, prec, rm))
                }
            }
        }

        // ── Floor ──────────────────────────────────────────────────
        ExprNode::Floor(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "floor of complex number is not defined".into(),
                });
            }
            // BigFloat::int() returns the integer part (truncation toward zero).
            // floor(x) = x if x is integer, else truncate toward -infinity.
            let truncated = val.0.int();
            let result = if val.0.is_negative() && truncated != val.0 {
                // For negative non-integers, floor = trunc - 1
                truncated.sub(&BigFloat::from_i32(1, prec), prec, rm)
            } else {
                truncated
            };
            Ok((result, BigFloat::new(prec)))
        }

        // ── Ceiling ────────────────────────────────────────────────
        ExprNode::Ceiling(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "ceiling of complex number is not defined".into(),
                });
            }
            let truncated = val.0.int();
            let result = if val.0.is_positive() && truncated != val.0 {
                // For positive non-integers, ceil = trunc + 1
                truncated.add(&BigFloat::from_i32(1, prec), prec, rm)
            } else {
                truncated
            };
            Ok((result, BigFloat::new(prec)))
        }

        // ── Min ────────────────────────────────────────────────────
        ExprNode::Min(children) => {
            if children.is_empty() {
                return Err(SymplexError::Unevaluable {
                    reason: "min of empty set".into(),
                });
            }
            let mut best = get_cached(cache, children[0])?.clone();
            if !best.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "min requires real arguments".into(),
                });
            }
            for &child in &children[1..] {
                let val = get_cached(cache, child)?;
                if !val.1.is_zero() {
                    return Err(SymplexError::Unevaluable {
                        reason: "min requires real arguments".into(),
                    });
                }
                if val.0.sub(&best.0, prec, rm).is_negative() {
                    best = val.clone();
                }
            }
            Ok(best)
        }

        // ── Max ────────────────────────────────────────────────────
        ExprNode::Max(children) => {
            if children.is_empty() {
                return Err(SymplexError::Unevaluable {
                    reason: "max of empty set".into(),
                });
            }
            let mut best = get_cached(cache, children[0])?.clone();
            if !best.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "max requires real arguments".into(),
                });
            }
            for &child in &children[1..] {
                let val = get_cached(cache, child)?;
                if !val.1.is_zero() {
                    return Err(SymplexError::Unevaluable {
                        reason: "max requires real arguments".into(),
                    });
                }
                if val.0.sub(&best.0, prec, rm).is_positive() {
                    best = val.clone();
                }
            }
            Ok(best)
        }

        // ── Heaviside ──────────────────────────────────────────────
        ExprNode::Heaviside(inner) => {
            let val = get_cached(cache, *inner)?;
            if !val.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "Heaviside of complex argument not supported in evalf".into(),
                });
            }
            if val.0.is_zero() {
                // H(0) = 0.5
                Ok((BigFloat::from_f64(0.5, prec), BigFloat::new(prec)))
            } else if val.0.is_negative() {
                Ok(c_zero(prec))
            } else {
                Ok((BigFloat::from_i32(1, prec), BigFloat::new(prec)))
            }
        }

        // ── DiracDelta ─────────────────────────────────────────────
        // Distributional: zero everywhere except at a single point of measure zero.
        ExprNode::DiracDelta(inner) => {
            let _val = get_cached(cache, *inner)?;
            // Numerically, δ(x) = 0 for all representable floats
            Ok(c_zero(prec))
        }

        // ── Apply-based special functions ───────────────────────────
        ExprNode::Apply(sid, args) => {
            let name = arena.symbol_name(*sid);
            match arena.lib_fn(*sid) {
                Some(LibFn::LambertW) => eval_lambertw_node(arena, node, cache, prec, rm, cc),
                Some(f) if f.arity().accepts(args.len()) => {
                    eval_lib_fn(f, args, cache, prec, rm, cc)
                }
                Some(_) => Err(unevaluable(format!(
                    "{name} called with {} argument(s)",
                    args.len()
                ))),
                // A user function has no numeric meaning.
                None => Err(unevaluable(format!("cannot evaluate function '{name}'"))),
            }
        }

        ExprNode::Derivative(_, _) => Err(SymplexError::Unevaluable {
            reason: "cannot evaluate unevaluated derivative".into(),
        }),

        ExprNode::Integral(_, _) => Err(SymplexError::Unevaluable {
            reason: "cannot evaluate unevaluated integral".into(),
        }),

        ExprNode::BoolTrue
        | ExprNode::BoolFalse
        | ExprNode::Gt(_, _)
        | ExprNode::Ge(_, _)
        | ExprNode::Eq_(_, _)
        | ExprNode::Ne(_, _)
        | ExprNode::And(_)
        | ExprNode::Or(_)
        | ExprNode::Not(_) => Err(SymplexError::Unevaluable {
            reason: "boolean expression".into(),
        }),

        ExprNode::EmptySet
        | ExprNode::UniversalSet
        | ExprNode::Interval(_, _, _)
        | ExprNode::FiniteSet(_)
        | ExprNode::SetUnion(_)
        | ExprNode::SetIntersection(_)
        | ExprNode::SetComplement(_, _) => Err(SymplexError::Unevaluable {
            reason: "set-valued expressions cannot be numerically evaluated".into(),
        }),

        ExprNode::Limit(_, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated Limit".into(),
        }),

        ExprNode::Series(_, _, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated Series".into(),
        }),

        ExprNode::LaplaceTransform(_, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated LaplaceTransform".into(),
        }),

        ExprNode::InverseLaplaceTransform(_, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated InverseLaplaceTransform".into(),
        }),

        ExprNode::Residue(_, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated Residue".into(),
        }),

        ExprNode::DSolve(_, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated DSolve".into(),
        }),

        ExprNode::ConditionSet(_, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate ConditionSet".into(),
        }),

        ExprNode::Subs(_, _, _) => Err(SymplexError::Unevaluable {
            reason: "cannot numerically evaluate unevaluated Subs".into(),
        }),
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Definite-integral helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Does the tree contain a `DefiniteIntegral` node?
fn contains_definite_integral(arena: &Arena, root: ExprId) -> bool {
    let mut stack = vec![root];
    let mut seen = rustc_hash::FxHashSet::default();
    while let Some(id) = stack.pop() {
        if !seen.insert(id) {
            continue;
        }
        let node = arena.node(id);
        if matches!(node, ExprNode::DefiniteIntegral(..)) {
            return true;
        }
        node.for_each_child(|c| stack.push(c));
    }
    false
}

/// An integration bound as `f64`, with a bound on its distance to the true
/// bound (the rounding to `f64`, and the evaluated value's own error):
/// `±∞` nodes directly (exact), anything else from the evaluated cache
/// (must be real).
fn definite_bound_f64(
    arena: &Arena,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    id: ExprId,
) -> Result<(f64, f64), SymplexError> {
    match arena.node(id) {
        ExprNode::Infinity => Ok((f64::INFINITY, 0.0)),
        ExprNode::NegInfinity => Ok((f64::NEG_INFINITY, 0.0)),
        _ => {
            let v = get_cached(cache, id)?;
            if !v.1.is_zero() {
                return Err(SymplexError::Unevaluable {
                    reason: "integration bounds of a definite integral must be real".into(),
                });
            }
            let x = bigfloat_to_f64_rounded(&v.0, RoundingMode::ToEven)?;
            let bound = errs.get(&id).copied().unwrap_or(accuracy::Bound::UNKNOWN);
            if bound.is_unknown() || !x.is_finite() {
                return Err(SymplexError::PrecisionExhausted {
                    requested: F64_DIGITS,
                    achieved: 0,
                });
            }
            let exp2 = |e: accuracy::ErrExp| {
                if accuracy::is_exact(e) {
                    0.0
                } else {
                    e.clamp(-1100.0, 1100.0).exp2()
                }
            };
            // |x − v| ≤ ½ ulp(x) ≤ |x|·2⁻⁵³; exact when `v` is an `f64`.
            let exact_in_f64 = BigFloat::from_f64(x, 64) == v.0;
            let conversion = if exact_in_f64 {
                0.0
            } else {
                x.abs() * f64::EPSILON / 2.0
            };
            Ok((x, conversion + exp2(bound.re) + exp2(bound.im)))
        }
    }
}

/// Multiple of `ε·∫|f|` (`ε = 2⁻⁵²`) that bounds the rounding of the `f64`
/// integrand values in a quadrature sum: each value carries a few roundings
/// of its own and the condition number of its evaluation (`sin(1/x)` near
/// `x = 10⁻³` loses three digits to the rounding of `1/x`).
const QUADRATURE_ROUNDING_FACTOR: f64 = 16.0;

/// Decimal digits served by [`evalf_complex64`] (`eval_f64`,
/// `eval_complex64`) for an expression containing a definite integral: the
/// `f64` Gauss–Kronrod estimate is returned when its error bound certifies
/// this many digits.  The quadrature seldom certifies the 16 digits of the
/// rest of the `f64` route (its own rounding floor is `50ε` per segment),
/// and before 0.29 it was served at a tolerance of `10⁻¹⁰`, accepted up to
/// `10⁻⁷`, with no check at all.
pub(crate) const QUADRATURE_F64_DIGITS: u32 = 8;

/// `∫_lo^hi body d(var)` by adaptive `f64` Gauss–Kronrod quadrature
/// ([`crate::calculus::definite::quadrature`]), with an honest error bound.
///
/// The body is compiled to a stack-VM function of the integration variable
/// (no arena mutation) and the bounds come from the cache (`±∞` allowed).
/// The quadrature is asked for the accuracy the working precision wants,
/// down to `10⁻¹³` relative (below that it only runs into its own
/// rounding floor).  The reported bound is the sum of
///
/// * the Gauss–Kronrod error estimate,
/// * the rounding of the `f64` integrand values,
///   [`QUADRATURE_ROUNDING_FACTOR`]`·ε·∫|f|` — `∫|f|`, not `|∫f|`, so an
///   oscillating integrand whose integral cancels is not credited with
///   digits its values do not have,
/// * the rounding of finite bounds to `f64` (and their own error) times the
///   largest integrand value seen,
///
/// so [`evaluate_adaptive`] refuses the digits the quadrature does not
/// have.  Before 0.29 the result was trusted to the working precision less
/// 16 bits: `eval_decimal(16)` of `∫₀¹ xˣ dx` printed
/// `0.7834305107121128` (mpmath: `0.78343051071213441…`), three wrong
/// digits.  A quadrature whose estimate is far above the default tolerance
/// (`10⁻⁷` relative) is taken as divergent, as before.
#[allow(clippy::too_many_arguments)]
fn eval_definite_integral(
    arena: &Arena,
    body: ExprId,
    var: ExprId,
    lo: ExprId,
    hi: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    prec: usize,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    use crate::calculus::definite::{QuadOpts, QuadResult, quadrature};
    debug!("evalf: DefiniteIntegral — f64 Gauss–Kronrod quadrature");
    let var_name = match arena.node(var) {
        ExprNode::Symbol(sid) => arena.symbol_name(*sid).to_string(),
        _ => {
            return Err(SymplexError::Unevaluable {
                reason: "integration variable of a definite integral must be a symbol".into(),
            });
        }
    };
    let (a, a_err) = definite_bound_f64(arena, cache, errs, lo)?;
    let (b, b_err) = definite_bound_f64(arena, cache, errs, hi)?;
    let func = crate::output::lambdify::compile_raw(arena, body, &[&var_name]).map_err(|e| {
        SymplexError::Unevaluable {
            reason: format!("definite integral body cannot be compiled for quadrature: {e}"),
        }
    })?;
    let peak = std::cell::Cell::new(0.0f64);
    let f = |t: f64| {
        let v = func(&[t]);
        if v.is_finite() {
            peak.set(peak.get().max(v.abs()));
        }
        v
    };
    // ∫|f|, to the accuracy a rounding estimate needs: the rounding floor
    // of the quadrature sum, below which its tolerance is pointless.
    let abs_f = |t: f64| func(&[t]).abs();
    let loose = QuadOpts {
        rel_tol: 1e-3,
        abs_tol: 0.0,
        max_subdivisions: 400,
    };
    let l1 = quadrature(&abs_f, a, b, &loose).map_or(f64::INFINITY, |r| r.value + r.error);
    let floor = QUADRATURE_ROUNDING_FACTOR * f64::EPSILON * l1;
    let default = QuadOpts::default();
    let wanted = 2f64.powi(
        -i32::try_from(prec.saturating_sub(64))
            .unwrap_or(i32::MAX)
            .min(1000),
    );
    let opts = QuadOpts {
        rel_tol: wanted.max(1e-13).min(default.rel_tol),
        abs_tol: if floor.is_finite() {
            floor
        } else {
            default.abs_tol
        },
        ..default
    };
    let QuadResult { value, error } = quadrature(&f, a, b, &opts)?;
    let tol = default.abs_tol.max(default.rel_tol * value.abs());
    // A NaN estimate is not converged either.
    let converged = error <= 1e3 * tol;
    if !converged {
        return Err(SymplexError::ComputationFailed {
            operation: "evalf",
            reason: format!(
                "quadrature of the definite integral did not converge: estimate {value} \
                 with error {error:e} (integral may diverge)"
            ),
        });
    }
    let rounding = QUADRATURE_ROUNDING_FACTOR * f64::EPSILON * l1.max(value.abs());
    let endpoints = (a_err + b_err) * peak.get();
    let total = error + rounding + endpoints;
    debug!(
        value,
        error, rounding, endpoints, "evalf: DefiniteIntegral evaluated"
    );
    if !value.is_finite() || !total.is_finite() {
        return Ok((
            (BigFloat::from_f64(value, prec), BigFloat::new(prec)),
            accuracy::Bound::UNKNOWN,
        ));
    }
    // A zero bound (a zero integrand at every node) is no proof of an
    // exact zero: the smallest subnormal.
    let e = if total > 0.0 {
        total.log2() + 1e-12
    } else {
        -1074.0
    };
    Ok((
        (BigFloat::from_f64(value, prec), BigFloat::new(prec)),
        accuracy::Bound::real(e),
    ))
}

// ═══════════════════════════════════════════════════════════════════════════
// Sub-tree evaluation helpers (Sum, Product, Piecewise, RootOf, RootSum)
// ═══════════════════════════════════════════════════════════════════════════

/// Most terms of a finite `Sum` or `Product` evaluated numerically.
const MAX_RANGE_TERMS: u32 = 10_000;

/// The value and error bound of `expr` (with post-order `post_order`) at
/// the integer `k` for the bound variable `var`: the index is exact when
/// it fits the precision.
#[allow(clippy::too_many_arguments)]
fn evaluate_at_integer(
    arena: &Arena,
    expr: ExprId,
    post_order: &[ExprId],
    var: ExprId,
    k: &BigInt,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    let value = (
        crate::base::numeric::bigint_to_bigfloat(k, prec),
        BigFloat::new(prec),
    );
    let err = if k.bits() <= prec as u64 {
        accuracy::EXACT
    } else {
        accuracy::rounding(&value, prec)
    };
    evaluate_tree(
        arena,
        expr,
        post_order,
        Some((var, value, accuracy::Bound::real(err))),
        true,
        prec,
        rm,
        cc,
    )
}

/// A bound of a `Sum` or `Product` range as an integer: an integer literal
/// exactly, another value when it is real and within `10⁻⁹` of an integer.
fn range_bound(
    arena: &Arena,
    cache: &FxHashMap<ExprId, Complex>,
    id: ExprId,
    what: &str,
    rm: RoundingMode,
) -> Result<BigInt, SymplexError> {
    if let Some(q) = arena.as_num(id) {
        if q.is_integer() {
            return Ok(q.to_integer());
        }
        return Err(unevaluable(format!("{what} bounds are not integers")));
    }
    let v = get_cached(cache, id)?;
    if !v.1.is_zero() {
        return Err(unevaluable(format!("{what} bounds must be real")));
    }
    let f = bigfloat_to_f64_rounded(&v.0, rm)?;
    let r = f.round();
    if !r.is_finite() || (f - r).abs() > 1e-9 || r.abs() > 9.0e15 {
        return Err(unevaluable(format!("{what} bounds are not integers")));
    }
    Ok(BigInt::from(r as i64))
}

/// The number of terms of `lo..=hi` (0 when empty), refused beyond
/// [`MAX_RANGE_TERMS`].
fn range_terms(lo: &BigInt, hi: &BigInt, what: &str) -> Result<u32, SymplexError> {
    if hi < lo {
        return Ok(0);
    }
    let n = hi - lo + 1;
    match u32::try_from(n) {
        Ok(n) if n <= MAX_RANGE_TERMS + 1 => Ok(n),
        _ => Err(unevaluable(format!(
            "{what} range too large for numerical evaluation (> {MAX_RANGE_TERMS} terms)"
        ))),
    }
}

/// A running sum of values with error bounds: per part, the terms' bounds
/// add, and every partial sum is rounded to the working precision
/// ([`accuracy::PartSum`]); a part that is an exact 0 in every term stays
/// exact (a sum of real terms is real).
struct SumAcc {
    value: Complex,
    re: accuracy::PartSum,
    im: accuracy::PartSum,
    unknown: bool,
    prec: usize,
}

impl SumAcc {
    fn new(prec: usize) -> SumAcc {
        SumAcc {
            value: c_zero(prec),
            re: accuracy::PartSum::new(),
            im: accuracy::PartSum::new(),
            unknown: false,
            prec,
        }
    }

    fn add(&mut self, term: &Complex, err: accuracy::Bound, rm: RoundingMode) {
        self.value = c_add(&self.value, term, self.prec, rm);
        self.unknown |= err.is_unknown();
        self.re.add(&term.0, err.re, &self.value.0, self.prec);
        self.im.add(&term.1, err.im, &self.value.1, self.prec);
    }

    /// The sum and its error bound.
    fn finish(self) -> (Complex, accuracy::Bound) {
        if self.unknown {
            return (self.value, accuracy::Bound::UNKNOWN);
        }
        let bound = accuracy::Bound {
            re: self.re.bound(),
            im: self.im.bound(),
        };
        (self.value, bound)
    }
}

/// `Σ_{var = lo}^{hi} body`: a finite range of at most [`MAX_RANGE_TERMS`]
/// terms term by term, `hi = ∞` as a hypergeometric series ([`hypsum`]).
/// The bound is the terms' bounds plus the roundings (before 0.29 it was
/// the working precision whatever the terms lost, and an infinite sum was
/// `Unevaluable`).
#[allow(clippy::too_many_arguments)]
fn eval_sum(
    arena: &Arena,
    body: ExprId,
    var: ExprId,
    lo: ExprId,
    hi: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    if matches!(arena.node(lo), ExprNode::NegInfinity) {
        return Err(unevaluable("a Sum from −∞ is not evaluated numerically"));
    }
    let lo_i = range_bound(arena, cache, lo, "Sum", rm)?;
    let post_order = walk::post_order_ids(arena, body);
    if matches!(arena.node(hi), ExprNode::Infinity) {
        if let Some(result) = emsum::rational_sum(arena, body, var, &lo_i, prec) {
            debug!("evalf: Sum — infinite sum of a rational term");
            return result;
        }
        debug!("evalf: Sum — infinite hypergeometric series");
        let mut term =
            |k: &BigInt, p: usize| evaluate_at_integer(arena, body, &post_order, var, k, p, rm, cc);
        return hypsum::infinite_sum(arena, body, var, &lo_i, prec, rm, &mut term);
    }
    let hi_i = range_bound(arena, cache, hi, "Sum", rm)?;
    let terms = range_terms(&lo_i, &hi_i, "Sum")?;
    let mut sum = SumAcc::new(prec);
    let mut k = lo_i.clone();
    for _ in 0..terms {
        let (term, err) = evaluate_at_integer(arena, body, &post_order, var, &k, prec, rm, cc)?;
        sum.add(&term, err, rm);
        k += 1;
    }
    debug!(lo = %lo_i, hi = %hi_i, "evalf: Sum evaluated");
    Ok(sum.finish())
}

/// `∏_{var = lo}^{hi} body` over a finite range of at most
/// [`MAX_RANGE_TERMS`] terms, bounded as a product of its terms.
#[allow(clippy::too_many_arguments)]
fn eval_product(
    arena: &Arena,
    body: ExprId,
    var: ExprId,
    lo: ExprId,
    hi: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    let lo_i = range_bound(arena, cache, lo, "Product", rm)?;
    let hi_i = range_bound(arena, cache, hi, "Product", rm)?;
    let terms = range_terms(&lo_i, &hi_i, "Product")?;
    let post_order = walk::post_order_ids(arena, body);
    let mut factors: Vec<(Complex, accuracy::Bound)> = Vec::with_capacity(terms as usize);
    let mut k = lo_i.clone();
    for _ in 0..terms {
        factors.push(evaluate_at_integer(
            arena,
            body,
            &post_order,
            var,
            &k,
            prec,
            rm,
            cc,
        )?);
        k += 1;
    }
    let parts: Vec<(&Complex, accuracy::Bound)> = factors.iter().map(|(v, e)| (v, *e)).collect();
    debug!(lo = %lo_i, hi = %hi_i, "evalf: Product evaluated");
    Ok(accuracy::mul_with_bound(&parts, prec, rm))
}

/// A condition decided from the values of its operands.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Decision {
    /// The truth value read off the computed values.
    value: bool,
    /// Does it hold for the true values too?  Every comparison involved
    /// was of exact values, or of a difference outside its error ball.
    certain: bool,
}

/// Decide a boolean condition numerically from the evaluated operands and
/// their error bounds.
///
/// A relation compares the difference of its operands (`Gt`, `Ge` need
/// both real); the decision is certain when both operands are exact (the
/// sign of a rounded difference of exact values is exact) or the same
/// expression, or when the difference is outside its error ball — as
/// `sign` is decided (see [`accuracy`]).  So an equality of distinct
/// inexact expressions is never certain, nor is an order between operands
/// whose imaginary parts are only within their error of 0 (they may not be
/// real).  `And`/`Or`/`Not` combine decisions; a certain `false`
/// operand decides an `And` (a certain `true` an `Or`) whatever the others.
/// `None` when an operand is missing from the cache (free symbol, complex
/// value in an order, unsupported node).
fn decide_condition(
    arena: &Arena,
    cond: ExprId,
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    prec: usize,
    rm: RoundingMode,
) -> Option<Decision> {
    let bound_of = |a: &ExprId| errs.get(a).copied().unwrap_or(accuracy::Bound::UNKNOWN);
    // `a − b`, the exponent of its (joint) error bound, and whether it is
    // exact (both operands exact, or the same expression).
    let difference = |a: &ExprId, b: &ExprId| -> Option<(Complex, accuracy::ErrExp, bool)> {
        let (av, bv) = (cache.get(a)?, cache.get(b)?);
        if a == b {
            return Some((c_zero(prec), accuracy::EXACT, true));
        }
        let (ea, eb) = (bound_of(a), bound_of(b));
        let d = c_sub(av, bv, prec + 64, rm);
        let exact = ea.is_exact() && eb.is_exact();
        let e = if ea.is_unknown() || eb.is_unknown() {
            accuracy::UNKNOWN
        } else {
            // The operands' errors add; the difference rounds at `prec + 64`.
            accuracy::lsum(
                accuracy::lsum(ea.joint(), eb.joint()),
                accuracy::rounding(&d, prec + 64),
            )
        };
        Some((d, e, exact))
    };
    let away_from_zero = |d: &Complex, e: accuracy::ErrExp| {
        !accuracy::is_unknown(e) && !accuracy::contains_zero(d, e)
    };
    let order = |a: &ExprId, b: &ExprId, strict: bool| -> Option<Decision> {
        let (av, bv) = (cache.get(a)?, cache.get(b)?);
        if !(av.1.is_zero() && bv.1.is_zero()) {
            return None;
        }
        let real =
            accuracy::exactly_real(av, bound_of(a)) && accuracy::exactly_real(bv, bound_of(b));
        let (d, e, exact) = difference(a, b)?;
        let value = d.0.is_positive() || (!strict && d.0.is_zero());
        Some(Decision {
            value,
            certain: exact || (real && away_from_zero(&d, e)),
        })
    };
    let equal = |a: &ExprId, b: &ExprId| -> Option<Decision> {
        let (d, e, exact) = difference(a, b)?;
        let value = d.0.is_zero() && d.1.is_zero();
        Some(Decision {
            value,
            certain: exact || (!value && away_from_zero(&d, e)),
        })
    };

    let post_order = walk::post_order_ids(arena, cond);
    let mut truth: FxHashMap<ExprId, Option<Decision>> = FxHashMap::default();
    for &id in &post_order {
        let kids = |ids: &[ExprId]| -> Vec<Option<Decision>> {
            ids.iter()
                .map(|k| truth.get(k).copied().flatten())
                .collect()
        };
        let v: Option<Decision> = match arena.node(id) {
            ExprNode::BoolTrue => Some(Decision {
                value: true,
                certain: true,
            }),
            ExprNode::BoolFalse => Some(Decision {
                value: false,
                certain: true,
            }),
            ExprNode::Gt(a, b) => order(a, b, true),
            ExprNode::Ge(a, b) => order(a, b, false),
            ExprNode::Eq_(a, b) => equal(a, b),
            ExprNode::Ne(a, b) => equal(a, b).map(|d| Decision {
                value: !d.value,
                ..d
            }),
            ExprNode::Not(inner) => truth.get(inner).copied().flatten().map(|d| Decision {
                value: !d.value,
                ..d
            }),
            ExprNode::And(ks) => combine(&kids(ks), false),
            ExprNode::Or(ks) => combine(&kids(ks), true),
            // Numeric operands and anything else carry no truth value.
            _ => None,
        };
        truth.insert(id, v);
    }
    truth.get(&cond).copied().flatten()
}

/// `Or` (`absorbing = true`) or `And` (`false`) of decisions: a certain
/// absorbing operand decides; otherwise every operand must be decided, and
/// the result is certain when they all are.
fn combine(operands: &[Option<Decision>], absorbing: bool) -> Option<Decision> {
    let certain_absorbing = Decision {
        value: absorbing,
        certain: true,
    };
    if operands.contains(&Some(certain_absorbing)) {
        return Some(certain_absorbing);
    }
    let decided: Option<Vec<Decision>> = operands.iter().copied().collect();
    let decided = decided?;
    Some(Decision {
        value: if absorbing {
            decided.iter().any(|d| d.value)
        } else {
            decided.iter().all(|d| d.value)
        },
        certain: decided.iter().all(|d| d.certain),
    })
}

/// `Piecewise`: the value of the first branch whose condition is true.
///
/// Conditions are decided in order ([`decide_condition`]).  An undecidable
/// condition is an error — falling through to a later `True` branch would
/// be silently wrong.  A decision that is not certain (a difference within
/// its error of 0) still picks a branch, but the result then has no bound,
/// so the evaluation is repeated at a higher precision and refused when
/// the budget is spent, as `sign` of such a difference is.  Before 0.29 the
/// decision was read off the rounded values: `Piecewise((0, x < √2), (1,
/// True))` at `x = √2 + 10⁻¹⁰⁰` came out `0`.
fn eval_piecewise(
    arena: &Arena,
    pairs: &[(ExprId, ExprId)],
    cache: &FxHashMap<ExprId, Complex>,
    errs: &ErrMap,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    debug!(
        branches = pairs.len(),
        "evalf: Piecewise — evaluating conditions"
    );
    let mut certain = true;
    for &(value_id, cond_id) in pairs {
        let Some(decision) = decide_condition(arena, cond_id, cache, errs, prec, rm) else {
            return Err(unevaluable(format!(
                "cannot evaluate piecewise: condition `{}` is undecided",
                arena.display(cond_id)
            )));
        };
        certain &= decision.certain;
        if !decision.value {
            continue;
        }
        let (value, err) = match cache.get(&value_id) {
            Some(v) => (
                v.clone(),
                errs.get(&value_id)
                    .copied()
                    .unwrap_or(accuracy::Bound::UNKNOWN),
            ),
            None => eval_node_with_error(arena, value_id, cache, errs, prec, rm, cc)?,
        };
        return Ok((
            value,
            if certain {
                err
            } else {
                accuracy::Bound::UNKNOWN
            },
        ));
    }
    if !certain {
        // A condition found false only to this precision may be true: no
        // value is known yet.
        return Ok((c_zero(prec), accuracy::Bound::UNKNOWN));
    }
    Err(unevaluable(
        "cannot evaluate piecewise: every condition is false",
    ))
}

/// The error bound of a root ball: its certified radius on both parts of a
/// non-real root, on the real part of a root certified real (whose
/// imaginary part is exactly 0); no bound without a certified radius.
fn radius_error(ball: &crate::poly::roots::RootBall) -> accuracy::Bound {
    let e = match ball.radius.as_ref() {
        None => return accuracy::Bound::UNKNOWN,
        Some(r) if r.is_zero() => accuracy::EXACT,
        Some(r) => accuracy::part_lg(r),
    };
    if ball.real {
        accuracy::Bound::real(e)
    } else {
        accuracy::Bound::both(e)
    }
}

/// `RootOf(poly, var, index)`: the `index`-th entry of
/// [`rootof_roots`](crate::poly::roots::rootof_roots) of `poly` as a
/// polynomial in `var`, bounded by the radius of its certified inclusion
/// disk ([`root_balls`](crate::poly::roots::root_balls)).  A root certified
/// real has an exactly zero imaginary part; without an isolating disk there
/// is no bound.
fn eval_rootof(
    arena: &Arena,
    poly_id: ExprId,
    var_id: ExprId,
    idx_id: ExprId,
    prec: usize,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    let idx: usize = match arena.as_num(idx_id) {
        Some(r) if r.is_integer() => {
            let n: i64 = r
                .to_integer()
                .try_into()
                .map_err(|_| unevaluable("RootOf index out of range"))?;
            usize::try_from(n).map_err(|_| unevaluable("RootOf index must be non-negative"))?
        }
        Some(_) => return Err(unevaluable("RootOf index must be an integer")),
        None => return Err(unevaluable("RootOf index must be numeric")),
    };
    let poly = crate::poly::polybridge::expr_to_poly(arena, poly_id, var_id)
        .ok_or_else(|| unevaluable("could not convert RootOf expression to polynomial"))?;
    // The roots with multiplicity in the (re, im) order of `rootof_roots`,
    // the one definition of the order a `RootOf` index refers to
    // (`real_roots` derives its indices from the same call).
    let balls = crate::poly::roots::certified_roots(&poly, prec);
    let found = balls.len();
    let ball = balls.into_iter().nth(idx).ok_or_else(|| {
        unevaluable(format!(
            "RootOf index {idx} exceeds the {found} root(s) found"
        ))
    })?;
    let err = radius_error(&ball);
    Ok((ball.value, err))
}

/// `RootSum(poly, body, sumvar) = Σ_{α: poly(α) = 0} body(α)`: the body at
/// every root found by Aberth's method, each root bounded by its certified
/// inclusion disk.  A body with other free variables fails.
fn eval_rootsum(
    arena: &Arena,
    poly_id: ExprId,
    body_id: ExprId,
    sumvar_id: ExprId,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(Complex, accuracy::Bound), SymplexError> {
    debug!("evalf: RootSum — attempting numerical evaluation via Aberth roots");
    let poly =
        crate::poly::polybridge::expr_to_poly(arena, poly_id, sumvar_id).ok_or_else(|| {
            unevaluable(
                "RootSum: cannot convert polynomial expression to Poly (may contain free symbols)",
            )
        })?;
    let degree = poly.degree().unwrap_or(0);
    let balls = crate::poly::roots::certified_roots(&poly, prec);
    if balls.len() != degree {
        debug!(
            expected = degree,
            found = balls.len(),
            "evalf: RootSum — fewer roots than expected"
        );
        return Err(unevaluable(
            "RootSum: not every root of the polynomial was found",
        ));
    }
    let n_roots = balls.len();
    let post_order = walk::post_order_ids(arena, body_id);
    let mut sum = SumAcc::new(prec);
    for ball in balls {
        let err = radius_error(&ball);
        let seed = Some((sumvar_id, ball.value, err));
        let (term, e) = evaluate_tree(arena, body_id, &post_order, seed, true, prec, rm, cc)?;
        sum.add(&term, e, rm);
    }
    debug!(n_roots, "evalf: RootSum — evaluated");
    Ok(sum.finish())
}

// ═══════════════════════════════════════════════════════════════════════════
// Complex arithmetic helpers
// ═══════════════════════════════════════════════════════════════════════════

// The field operations live in `base::bigcomplex` (shared with the root
// finders and algebraic-number verification); the transcendental ones
// below need this module's constant cache.
pub(crate) use crate::base::bigcomplex::{
    c_abs, c_add, c_div, c_from_real, c_i, c_mul, c_neg, c_one, c_powi, c_sub, c_zero,
};

fn c_exp(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // exp(a+bi) = exp(a)(cos(b) + i·sin(b))
    let exp_a = z.0.exp(prec, rm, cc);
    let (sin_b, cos_b) = sin_cos(&z.1, prec, rm, cc);
    (exp_a.mul(&cos_b, prec, rm), exp_a.mul(&sin_b, prec, rm))
}

/// `(sin x, cos x)`, exact at `x ∈ {0, ±π/2, ±π}` when `x` is bit for bit
/// the working-precision constant.
///
/// The evaluator produces exactly those constants itself — `arg` of a
/// negative real is π, `asin` of a real beyond 1 has real part ±π/2 — and
/// `sin` of the *rounded* π is a residue of about `2^(−prec)`, not 0.
/// Carried on, that residue picks the side of the next branch cut by its
/// sign: `exp(ln(−5/7))` came out `−5/7 + 1e-50·i`, and
/// `acosh(1/exp(ln x))` at `x = −5/7` the conjugate of `acosh(−7/5)`.  A
/// value equal to the rounded π is indistinguishable from π at this
/// precision, so its exact sine is the right answer.
fn sin_cos(x: &BigFloat, prec: usize, rm: RoundingMode, cc: &mut Consts) -> (BigFloat, BigFloat) {
    let zero = BigFloat::new(prec);
    let one = BigFloat::from_i32(1, prec);
    if x.is_zero() {
        return (zero, one);
    }
    let pi = cc.pi(prec, rm).clone();
    let half_pi = pi.div(&BigFloat::from_i32(2, prec), prec, rm);
    if *x == half_pi {
        return (one, zero);
    }
    if *x == half_pi.neg() {
        return (one.neg(), zero);
    }
    if *x == pi || *x == pi.neg() {
        return (zero, one.neg());
    }
    (x.sin(prec, rm, cc), x.cos(prec, rm, cc))
}

fn c_ln(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // ln(z) = ln|z| + i·arg(z)
    let r = c_abs(z, prec, rm);
    let theta = atan2_bf(&z.1, &z.0, prec, rm, cc);
    (r.ln(prec, rm, cc), theta)
}

fn c_sin(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // sin(a+bi) = sin(a)cosh(b) + i·cos(a)sinh(b)
    let (sin_a, cos_a) = sin_cos(&z.0, prec, rm, cc);
    let cosh_b = z.1.cosh(prec, rm, cc);
    let sinh_b = z.1.sinh(prec, rm, cc);
    (sin_a.mul(&cosh_b, prec, rm), cos_a.mul(&sinh_b, prec, rm))
}

fn c_cos(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // cos(a+bi) = cos(a)cosh(b) - i·sin(a)sinh(b)
    let (sin_a, cos_a) = sin_cos(&z.0, prec, rm, cc);
    let cosh_b = z.1.cosh(prec, rm, cc);
    let sinh_b = z.1.sinh(prec, rm, cc);
    (
        cos_a.mul(&cosh_b, prec, rm),
        sin_a.mul(&sinh_b, prec, rm).neg(),
    )
}

fn c_sinh(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // sinh(a+bi) = sinh(a)cos(b) + i·cosh(a)sin(b)
    let sinh_a = z.0.sinh(prec, rm, cc);
    let cosh_a = z.0.cosh(prec, rm, cc);
    let (sin_b, cos_b) = sin_cos(&z.1, prec, rm, cc);
    (sinh_a.mul(&cos_b, prec, rm), cosh_a.mul(&sin_b, prec, rm))
}

fn c_cosh(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // cosh(a+bi) = cosh(a)cos(b) + i·sinh(a)sin(b)
    let cosh_a = z.0.cosh(prec, rm, cc);
    let sinh_a = z.0.sinh(prec, rm, cc);
    let (sin_b, cos_b) = sin_cos(&z.1, prec, rm, cc);
    (cosh_a.mul(&cos_b, prec, rm), sinh_a.mul(&sin_b, prec, rm))
}

fn c_pow(base: &Complex, exp: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // base^exp = exp(exp * ln(base))
    // Special case: base is zero.
    if base.0.is_zero() && base.1.is_zero() {
        // 0^0 = 1 by convention; 0^(positive) = 0.
        if exp.0.is_zero() && exp.1.is_zero() {
            return c_one(prec);
        }
        return c_zero(prec);
    }
    let ln_base = c_ln(base, prec, rm, cc);
    let product = c_mul(exp, &ln_base, prec, rm);
    c_exp(&product, prec, rm, cc)
}

fn c_sqrt(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    if z.0.is_zero() && z.1.is_zero() {
        return c_zero(prec);
    }
    let half = c_from_real(
        BigFloat::from_i32(1, prec).div(&BigFloat::from_i32(2, prec), prec, rm),
        prec,
    );
    c_pow(z, &half, prec, rm, cc)
}

// ── Inverse trig (complex) ─────────────────────────────────────────

/// `asin`, `atan`, `asinh` and `atanh` of a complex `z` are `z·(1 + O(z²))`,
/// but their logarithmic formulas take `ln(1 + O(z))`: rounding `1 ± iz`
/// to `prec` bits is an absolute error of `2^−prec`, `log₂(1/|z|)` bits of
/// the value that the node's bound (its rounding at the value's magnitude)
/// does not know of.  `f(z, prec)` is evaluated with that many more bits and
/// rounded; below `2^−prec` the value is `z` itself.  Before 0.30 neither:
/// `atan(i·10⁻³⁰)` was `9.99999998762973·10⁻³¹·i` at 16 digits (truly
/// `1·10⁻³⁰·i`).
fn small_argument(
    z: &Complex,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
    f: fn(&Complex, usize, RoundingMode, &mut Consts) -> Complex,
) -> Complex {
    let m = accuracy::mag(z).unwrap_or(0);
    if m >= 0 {
        return f(z, prec, rm, cc);
    }
    let lost = usize::try_from(-m).unwrap_or(usize::MAX);
    if lost > prec + 8 {
        return (
            round_to(z.0.clone(), prec, rm),
            round_to(z.1.clone(), prec, rm),
        );
    }
    let v = f(z, prec + lost + 16, rm, cc);
    (round_to(v.0, prec, rm), round_to(v.1, prec, rm))
}

fn c_asin(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    small_argument(z, prec, rm, cc, c_asin_at)
}

fn c_asin_at(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // asin(z) = −i·ln(iz + √(1 − z²)).  In half the plane the two terms
    // nearly cancel for large |z|; there the sum is taken as 1/(√(1 − z²) −
    // iz), the same number ((iz + s)(s − iz) = 1), without the cancellation.
    let i_unit = c_i(prec);
    let one = c_one(prec);
    let z_sq = c_mul(z, z, prec, rm);
    let one_minus_z_sq = c_sub(&one, &z_sq, prec, rm);
    let sqrt_term = c_sqrt(&one_minus_z_sq, prec, rm, cc);
    let iz = c_mul(&i_unit, z, prec, rm);
    let sum = sum_without_cancellation(&iz, &sqrt_term, prec, rm);
    let ln_sum = c_ln(&sum, prec, rm, cc);
    let neg_i = c_neg(&i_unit);
    c_mul(&neg_i, &ln_sum, prec, rm)
}

/// `a + s` for `a`, `s` with `s² − a² = 1` (then `(a + s)(s − a) = 1`):
/// the direct sum when it does not cancel, `1/(s − a)` when it does.
fn sum_without_cancellation(a: &Complex, s: &Complex, prec: usize, rm: RoundingMode) -> Complex {
    let plus = c_add(a, s, prec, rm);
    let minus = c_sub(s, a, prec, rm);
    if c_abs(&plus, prec, rm) >= c_abs(&minus, prec, rm) {
        plus
    } else {
        c_div(&c_one(prec), &minus, prec, rm)
    }
}

fn c_acos(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // acos(z) = pi/2 - asin(z)
    let half_pi_val = cc.pi(prec, rm).div(&BigFloat::from_i32(2, prec), prec, rm);
    let half_pi = c_from_real(half_pi_val, prec);
    let asin_z = c_asin(z, prec, rm, cc);
    c_sub(&half_pi, &asin_z, prec, rm)
}

fn c_atan(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    small_argument(z, prec, rm, cc, c_atan_at)
}

fn c_atan_at(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // atan(z) = (i/2)·(ln(1 − iz) − ln(1 + iz)).  The quotient form
    // (i/2)·ln((i + z)/(i − z)) differs from it by π on the cut
    // z ∈ i·(1, ∞) (atan(2i) would be −π/2 + …, mpmath says +π/2 + …).
    let one = c_one(prec);
    let iz = c_mul(&c_i(prec), z, prec, rm);
    let ln_minus = c_ln(&c_sub(&one, &iz, prec, rm), prec, rm, cc);
    let ln_plus = c_ln(&c_add(&one, &iz, prec, rm), prec, rm, cc);
    let diff = c_sub(&ln_minus, &ln_plus, prec, rm);
    let half = BigFloat::from_i32(1, prec).div(&BigFloat::from_i32(2, prec), prec, rm);
    // (i/2)·(a + bi) = −b/2 + (a/2)·i
    (
        diff.1.mul(&half, prec, rm).neg(),
        diff.0.mul(&half, prec, rm),
    )
}

// ── Inverse hyperbolic (complex) ──────────────────────────────────

fn c_asinh(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    small_argument(z, prec, rm, cc, c_asinh_at)
}

fn c_asinh_at(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // asinh(z) = ln(z + √(z² + 1)), the sum taken without cancellation
    // (it cancels for Re z < 0 and large |z|).
    let one = c_one(prec);
    let z_sq = c_mul(z, z, prec, rm);
    let z_sq_plus_one = c_add(&z_sq, &one, prec, rm);
    let sqrt_term = c_sqrt(&z_sq_plus_one, prec, rm, cc);
    let sum = sum_without_cancellation(z, &sqrt_term, prec, rm);
    c_ln(&sum, prec, rm, cc)
}

fn c_acosh(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // acosh(z) = ln(z + √(z + 1)·√(z − 1)).  The single root √(z² − 1)
    // is the other branch whenever Re z < 0 (acosh(−2 + i/2) came out
    // negated); the product of two roots is the principal value everywhere.
    let one = c_one(prec);
    let root_plus = c_sqrt(&c_add(z, &one, prec, rm), prec, rm, cc);
    let root_minus = c_sqrt(&c_sub(z, &one, prec, rm), prec, rm, cc);
    let sum = c_add(z, &c_mul(&root_plus, &root_minus, prec, rm), prec, rm);
    c_ln(&sum, prec, rm, cc)
}

fn c_atanh(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    small_argument(z, prec, rm, cc, c_atanh_at)
}

fn c_atanh_at(z: &Complex, prec: usize, rm: RoundingMode, cc: &mut Consts) -> Complex {
    // atanh(z) = (ln(1 + z) − ln(1 − z))/2.  The quotient form
    // ln((1 + z)/(1 − z))/2 differs from it by πi on the cut z ∈ (1, ∞).
    let one = c_one(prec);
    let ln_plus = c_ln(&c_add(&one, z, prec, rm), prec, rm, cc);
    let ln_minus = c_ln(&c_sub(&one, z, prec, rm), prec, rm, cc);
    let diff = c_sub(&ln_plus, &ln_minus, prec, rm);
    let half = BigFloat::from_i32(1, prec).div(&BigFloat::from_i32(2, prec), prec, rm);
    (diff.0.mul(&half, prec, rm), diff.1.mul(&half, prec, rm))
}

/// The real part of a trigonometric node's argument, and the bits it
/// carries beyond `prec`.  A rational child (`sin(10^100)`) is converted
/// again with `log₂|r|` extra bits, so that reducing it modulo 2π starts
/// from a value correct to `prec` bits after the point, not one rounded to
/// `prec` significant bits.
fn trig_arg(
    arena: &Arena,
    inner: ExprId,
    val: &Complex,
    prec: usize,
    rm: RoundingMode,
) -> (BigFloat, usize) {
    if let ExprNode::Num(nid) = arena.node(inner)
        && let Some(e) = val.0.exponent()
        && e > 0
        && val.0.inexact()
    {
        let extra = usize::try_from(e).unwrap_or(0);
        if extra <= arena.config.max_evalf_precision as usize {
            return (ratio_to_bigfloat(arena.num(*nid), prec + extra, rm), extra);
        }
    }
    (val.0.clone(), 0)
}

/// π/2 at `prec` bits.
fn half_pi_bf(prec: usize, rm: RoundingMode, cc: &mut Consts) -> BigFloat {
    cc.pi(prec, rm).div(&BigFloat::from_i32(2, prec), prec, rm)
}

/// `|x| ≤ 1`: the real domain of `asin`, `acos` and (open) `atanh`.
fn abs_le_one(x: &BigFloat, prec: usize) -> bool {
    x.abs() <= BigFloat::from_i32(1, prec)
}

/// Binary exponent above which an *inexact* trigonometric argument is
/// refused.  Reducing `x` modulo 2π turns its relative rounding error into
/// an absolute error of about `2^(e − prec)`, and [`evalf`] carries at least
/// 64 guard bits beyond the digits requested, so past `2^64` the reduction
/// eats into the digits that are printed.
const TRIG_ARG_MAX_INEXACT_EXPONENT: i64 = 64;

/// Refuse a trigonometric argument whose value is not known well enough to
/// reduce it modulo 2π at this precision: an inexact one of magnitude
/// ≥ `2^64` (see [`TRIG_ARG_MAX_INEXACT_EXPONENT`]; `exp(100) ≈ 2^144` at
/// 30 digits is known only to within about `2^(144 − 166)`), or any beyond
/// `EvalConfig::max_evalf_precision` bits — astro-float would compute π to
/// that many bits, and `cos(cosh(cosh(4i)))` ran for minutes.
///
/// `extra` is the number of bits `x` carries beyond `prec` (see
/// [`trig_arg`]); they widen the inexact bound by as much.
fn check_trig_arg(
    x: &BigFloat,
    extra: usize,
    prec: usize,
    arena: &Arena,
) -> Result<(), SymplexError> {
    let Some(e) = x.exponent() else {
        return Ok(());
    };
    let e = i64::from(e);
    let cap = i64::from(arena.config.max_evalf_precision);
    let bound =
        TRIG_ARG_MAX_INEXACT_EXPONENT.saturating_add(i64::try_from(extra).unwrap_or(i64::MAX));
    if e > cap || (x.inexact() && e > bound) {
        let digits = u32::try_from(prec.saturating_sub(64) * 10 / 34).unwrap_or(u32::MAX);
        return Err(SymplexError::PrecisionExhausted {
            requested: digits,
            achieved: 0,
        });
    }
    Ok(())
}

// ═══════════════════════════════════════════════════════════════════════════
// Real-valued helpers
// ═══════════════════════════════════════════════════════════════════════════

/// Compute atan2(y, x) using BigFloat arithmetic.
fn atan2_bf(
    y: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> BigFloat {
    if x.is_zero() && y.is_zero() {
        return BigFloat::new(prec);
    }
    // On the real axis the sign of a zero `y` is an accident of how the
    // value was computed (`c_neg` turns `+0` into `−0`), not a side of the
    // cut: a negative real has argument +π on the principal branch.
    if y.is_zero() {
        return if x.is_negative() {
            cc.pi(prec, rm).clone()
        } else {
            BigFloat::new(prec)
        };
    }

    let pi_val = cc.pi(prec, rm);
    let two = BigFloat::from_i32(2, prec);
    let half_pi = pi_val.div(&two, prec, rm);

    if x.is_zero() {
        return if y.is_positive() {
            half_pi
        } else {
            half_pi.neg()
        };
    }

    let ratio = y.div(x, prec, rm);
    let atan_val = ratio.atan(prec, rm, cc);

    if x.is_positive() {
        atan_val
    } else {
        let pi_val2 = cc.pi(prec, rm);
        if y.is_negative() {
            atan_val.sub(&pi_val2, prec, rm)
        } else {
            atan_val.add(&pi_val2, prec, rm)
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Special function helpers (f64-based)
// ═══════════════════════════════════════════════════════════════════════════

/// Convert a `BigFloat` to `f64`, rounding once from the binary mantissa
/// (see [`bigfloat_to_f64_rounded`]).
///
/// `_cc` is not needed by the binary rounding; the parameter stays so the
/// many call sites written for the earlier decimal-radix route are
/// unchanged.
fn bigfloat_to_f64(bf: &BigFloat, rm: RoundingMode, _cc: &mut Consts) -> Result<f64, SymplexError> {
    bigfloat_to_f64_rounded(bf, rm)
}

/// The `f64` nearest to a `BigFloat`, rounded straight from the binary
/// mantissa with `rm` as the tie rule (astro-float's modes are all
/// round-to-nearest with different tie-breaking; `None` truncates).
///
/// Zero maps to `+0.0`; `±∞` to `±INFINITY`.  A value beyond the `f64`
/// exponent range overflows to `±INFINITY` or underflows through the
/// subnormals to `±0.0`, as a decimal parse of it would.
///
/// # Errors
///
/// [`SymplexError::Unevaluable`] for NaN.
fn bigfloat_to_f64_rounded(bf: &BigFloat, rm: RoundingMode) -> Result<f64, SymplexError> {
    if bf.is_zero() {
        return Ok(0.0);
    }
    if bf.is_inf_pos() {
        return Ok(f64::INFINITY);
    }
    if bf.is_inf_neg() {
        return Ok(f64::NEG_INFINITY);
    }
    let Some((words, _, sign, exponent, _)) = bf.as_raw_parts() else {
        return Err(SymplexError::Unevaluable {
            reason: "NaN in BigFloat to f64 conversion".into(),
        });
    };
    let negative = sign == Sign::Neg;
    let signed = |v: f64| if negative { -v } else { v };

    // The mantissa words are little-endian and the value is
    // `0.m × 2^exponent`, so the leading bit is worth `2^(exponent − 1)`.
    // Gather the 64 most significant bits (the word size is 32 on wasm32)
    // and remember whether anything below them is set.
    let mut acc: u128 = 0;
    let mut filled = 0usize;
    let mut sticky = false;
    for &w in words.iter().rev() {
        if filled < 64 {
            acc = (acc << WORD_BIT_SIZE) | w as u128;
            filled += WORD_BIT_SIZE;
        } else if w != 0 {
            sticky = true;
        }
    }
    let top: u64 = if filled >= 64 {
        let extra = filled - 64;
        if extra > 0 && acc & ((1u128 << extra) - 1) != 0 {
            sticky = true;
        }
        (acc >> extra) as u64
    } else {
        (acc << (64 - filled)) as u64
    };
    if top & (1 << 63) == 0 {
        // Only astro-float's own subnormals (at its minimum exponent, far
        // below the f64 range) lack the leading bit.
        return Ok(signed(0.0));
    }

    let mut unbiased = exponent as i64 - 1;
    if unbiased > 1023 {
        return Ok(signed(f64::INFINITY));
    }
    // Significand bits the result can hold: 53 for a normal number, fewer
    // for a subnormal (`2^-1074` is the last representable bit).
    let keep = if unbiased >= -1022 {
        53
    } else {
        unbiased + 1075
    };
    // `mant`: the kept bits; `above_half` / `exactly_half`: the dropped
    // remainder against half a unit in the last kept place.
    let (mant, above_half, exactly_half) = if keep <= 0 {
        // Below the smallest subnormal `2^-1074`; `keep == 0` puts the
        // value in `[2^-1075, 2^-1074)`, at or above half of it.
        let at_half = top == 1 << 63 && !sticky;
        (0u64, keep == 0 && !at_half, keep == 0 && at_half)
    } else {
        let shift = (64 - keep) as u32;
        let mant = top >> shift;
        let rem = top & ((1u64 << shift) - 1);
        let half = 1u64 << (shift - 1);
        (
            mant,
            rem > half || (rem == half && sticky),
            rem == half && !sticky,
        )
    };
    let round_up = match rm {
        RoundingMode::None => false,
        _ if above_half => true,
        _ if !exactly_half => false,
        RoundingMode::Up => !negative,
        RoundingMode::Down => negative,
        RoundingMode::ToZero => false,
        RoundingMode::FromZero => true,
        RoundingMode::ToEven => mant & 1 == 1,
        RoundingMode::ToOdd => mant & 1 == 0,
    };
    let mut mant = mant + u64::from(round_up);

    let bits = if keep == 53 {
        if mant == 1 << 53 {
            // Rounded up into the next binade.
            mant >>= 1;
            unbiased += 1;
            if unbiased > 1023 {
                return Ok(signed(f64::INFINITY));
            }
        }
        (((unbiased + 1023) as u64) << 52) | (mant & ((1 << 52) - 1))
    } else {
        // Subnormal: the value is `mant × 2^-1074` and the bit pattern is
        // `mant` itself (`mant == 2^52` is the smallest normal number).
        mant
    };
    Ok(signed(f64::from_bits(bits)))
}

/// Lanczos approximation for the Gamma function (g=7, 9 coefficients).
#[allow(dead_code)]
#[allow(clippy::excessive_precision)]
fn lanczos_gamma_f64(x: f64) -> Result<f64, SymplexError> {
    if x.is_nan() || x.is_infinite() {
        return Err(SymplexError::Unevaluable {
            reason: "Gamma of special float value".into(),
        });
    }

    // Reflection formula for x < 0.5:  Gamma(x) = pi / (sin(pi*x) * Gamma(1-x))
    if x < 0.5 {
        let reflected = lanczos_gamma_f64(1.0 - x)?;
        let sin_pi_x = (std::f64::consts::PI * x).sin();
        if sin_pi_x.abs() < 1e-300 {
            return Err(SymplexError::Unevaluable {
                reason: "Gamma at non-positive integer pole".into(),
            });
        }
        let result = std::f64::consts::PI / (sin_pi_x * reflected);
        if result.is_finite() {
            return Ok(result);
        }
        return Err(SymplexError::Unevaluable {
            reason: "Gamma at pole".into(),
        });
    }

    // Lanczos approximation with g=7
    const COEFFICIENTS: [f64; 9] = [
        0.99999999999980993,
        676.5203681218851,
        -1259.1392167224028,
        771.32342877765313,
        -176.61502916214059,
        12.507343278686905,
        -0.13857109526572012,
        9.9843695780195716e-6,
        1.5056327351493116e-7,
    ];

    let x = x - 1.0; // Lanczos uses Gamma(x+1) = x!
    let t = x + 7.0 + 0.5; // g = 7

    let mut sum = COEFFICIENTS[0];
    for (i, &c) in COEFFICIENTS[1..].iter().enumerate() {
        sum += c / (x + i as f64 + 1.0);
    }

    let result = (2.0 * std::f64::consts::PI).sqrt() * t.powf(x + 0.5) * (-t).exp() * sum;
    Ok(result)
}

/// Error function via Taylor series (small |x|) or asymptotic expansion (large |x|).
#[allow(dead_code)]
fn erf_f64(x: f64) -> f64 {
    if x.abs() < 4.0 {
        // Taylor series: erf(x) = 2/sqrt(pi) * sum_{n=0}^{inf} (-1)^n * x^(2n+1) / (n! * (2n+1))
        let mut sum = 0.0;
        let mut term = x; // first term: x
        sum += term;
        for n in 1..50 {
            term *= -x * x / n as f64;
            sum += term / (2 * n + 1) as f64;
        }
        sum * 2.0 / std::f64::consts::PI.sqrt()
    } else {
        // For large |x|, use complementary: erf(x) = 1 - erfc(x)
        // erfc(x) ~ exp(-x^2)/(x*sqrt(pi)) * sum_{n=0} (-1)^n * (2n-1)!! / (2x^2)^n
        let sign = x.signum();
        let ax = x.abs();
        let mut sum = 1.0;
        let mut term = 1.0;
        for n in 1..20 {
            term *= -(2 * n - 1) as f64 / (2.0 * ax * ax);
            if term.abs() < 1e-16 {
                break;
            }
            sum += term;
        }
        let erfc = (-ax * ax).exp() / (ax * std::f64::consts::PI.sqrt()) * sum;
        sign * (1.0 - erfc)
    }
}

/// `loggamma(x)` for real `x` (not a pole): the analytic continuation of
/// `ln Γ` from `x > 0` (SymPy's and mpmath's `loggamma`), real for `x > 0`
/// and on the cut `x < 0` its limit from above, `ln|Γ(x)| − iπ⌈−x⌉`
/// (mpmath: `loggamma(-2.5) = −0.0562 − 3πi`).  Before 0.30 the value left
/// of 0 was the real `ln|Γ(x)|` (the compiled back-ends' `lgamma`, which is
/// now `ln(abs(gamma(x)))`).
///
/// * `x > 0`: Stirling's series ([`stirling_log_gamma`]).
/// * `x < 0`: real part `ln π − ln|sin πd| − ln Γ(1 − x)`, `d = x − round(x)`
///   exact; imaginary part `−π·⌈−x⌉ = π·⌊x⌋`.
///
/// Near a zero of `ln|Γ|` (`x = 1`, `2`, and two between consecutive poles
/// left of 0) the terms summed are much larger than the value: the loss is
/// measured against a bound on them and the evaluation repeated with that
/// many more bits, up to [`cancellation_cap`].  Before 0.29 neither:
/// `loggamma(1 + 2⁻¹⁰⁰)` was wrong from its 13th digit, `πx` was rounded
/// before `sin`, and arguments within `10⁻¹²` of a pole (in `f64`) were
/// refused as poles.
fn arb_log_gamma(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    if x.is_nan() || x.is_inf() {
        return Err(unevaluable("LogGamma of special float value"));
    }
    if (x.is_int() || x.is_zero()) && !bf_strictly_positive(x) {
        return Err(unevaluable("LogGamma at non-positive integer pole"));
    }
    let exact = x.mantissa_max_bit_len().unwrap_or(prec).max(prec) + 64;
    let cap = cancellation_cap(prec);
    // On the cut: −π·⌈−x⌉ = π·⌊x⌋, the limit from the upper half-plane.
    let imaginary = if bf_strictly_positive(x) {
        BigFloat::new(prec)
    } else {
        let pi = cc.pi(prec + 16, rm).clone();
        round_to(pi.mul(&x.floor(), prec + 16, rm), prec, rm)
    };
    // The first attempt covers the terms' bits (a value of magnitude 2⁻⁸
    // and up needs no second one).
    let zs0 = bigfloat_to_f64(&x.abs(), rm, cc)?.min(1e300) + 0.5 * (prec + 48) as f64 + 3.0;
    let mut extra = (24 + terms_bits(2.0 * zs0 * (zs0.ln() + 1.0)).max(0) as usize).min(cap);
    loop {
        let wp = prec + extra;
        // The value and a bound on the terms summed.
        let (value, largest) = if bf_strictly_positive(x) {
            // Stirling at z + s, s ‹ 0.5·wp: terms up to (z+s)·(|ln(z+s)| + 1),
            // and the shift Σ ln(z + i) below that.
            let v = stirling_log_gamma(x, wp, rm, cc)?;
            let zs = bigfloat_to_f64(x, rm, cc)?.max(0.0) + 0.5 * wp as f64 + 2.0;
            (v, 2.0 * zs * (zs.ln() + 1.0))
        } else {
            let n = x.add(&BigFloat::from_f64(0.5, 64), exact, rm).floor();
            let d = x.sub(&n, exact, rm);
            let pi = cc.pi(wp, rm).clone();
            let ln_sin = pi.mul(&d, wp, rm).sin(wp, rm, cc).abs().ln(wp, rm, cc);
            let one_minus_x = BigFloat::from_i32(1, 64).sub(x, exact, rm);
            let lg1 = stirling_log_gamma(&one_minus_x, wp, rm, cc)?;
            let ln_pi = pi.ln(wp, rm, cc);
            let v = ln_pi.sub(&ln_sin, wp, rm).sub(&lg1, wp, rm);
            let zs = bigfloat_to_f64(&one_minus_x, rm, cc)? + 0.5 * wp as f64 + 2.0;
            let terms = 2.0 * zs * (zs.ln() + 1.0) + bigfloat_to_f64(&ln_sin, rm, cc)?.abs() + 2.0;
            (v, terms)
        };
        // The loss relative to the whole value: on the cut its imaginary
        // part, at least π, bounds it below (a zero of ln|Γ| there costs no
        // extra bits).
        let magnitude = match (value.exponent(), imaginary.exponent()) {
            _ if value.is_zero() && imaginary.is_zero() => None,
            (Some(e), Some(i)) if !value.is_zero() && !imaginary.is_zero() => Some(e.max(i)),
            (Some(e), _) if !value.is_zero() => Some(e),
            (_, i) => i,
        };
        let lost = match magnitude {
            Some(e) => (terms_bits(largest) - i64::from(e)).max(0) as usize,
            None => wp,
        };
        if lost + 16 <= extra {
            return Ok((round_to(value, prec, rm), imaginary));
        }
        if extra >= cap {
            return Err(special_exhausted(prec));
        }
        extra = (lost + 32).max(2 * extra).min(cap);
    }
}

/// A precision at which a sum or difference of `x` and a small integer is
/// exact (or within `2^−64` of it relative to its larger operand's bits).
fn exact_bits(x: &BigFloat, prec: usize) -> usize {
    // The lowest bit of `x` is at `e − m`; `x + c` for `|c| < 2^62` reaches
    // up to `max(e, 62)`.  Before 0.30 only `m + 64` bits: a tiny `x` lost
    // its bits in `x − k + 1`, and `binomial(10⁻⁷⁰, 6)` — `Γ` next to its
    // pole at `−5` — was wrong from its 8th digit.
    // (At most 2¹⁶ bits for the offset: beyond, `x + c` rounds to `c`, and
    // a pole of `Γ` there is refused rather than met with a million-bit
    // number.)
    let m = x.mantissa_max_bit_len().unwrap_or(prec).max(prec);
    let below = x.exponent().map_or(0, |e| {
        usize::try_from(64 - i64::from(e)).unwrap_or(0).min(1 << 16)
    });
    m + below + 64
}

/// `⌈log₂ v⌉ + 1` for a positive `f64` magnitude bound (`i64::MAX/4` beyond
/// range).
fn terms_bits(v: f64) -> i64 {
    if v.is_finite() && v > 0.0 {
        v.log2().ceil() as i64 + 1
    } else {
        i64::MAX / 4
    }
}

/// `ψ(x)` for real `x` (not a pole) to a relative error of about `2^−prec`.
///
/// 1. `x < 0`: the reflection `ψ(x) = ψ(1 − x) − π cot(πd)`, `d = x − round(x)`
///    exact (`cot` has period 1), so a pole is only an integer `x` and `πd`
///    is rounded relative to `d`, not to `x`.
/// 2. `x > 0`: `ψ(x) = ψ(x + N) − Σ_{k<N} 1/(x + k)` with `x + N ≥ wp/3`.
/// 3. `ψ(y) ~ ln y − 1/(2y) − Σ_{k≥1} B_{2k}/(2k·y^{2k})` (DLMF 5.11.2), with
///    exact Bernoulli numbers until a term is below the working precision
///    (the smallest term, near `k ≈ πy`, is `~e^{−2πy}`).
///
/// Near a zero of `ψ` (`x₀ = 1.4616…`, and one between consecutive poles
/// left of 0) the terms are much larger than the value: the loss, `log₂` of
/// the largest term over the result, is measured and the evaluation
/// repeated with that many more bits, up to [`cancellation_cap`].  Before
/// 0.29 the series stopped after 12 terms and the loss went unmeasured:
/// `digamma(1/3)` was wrong from its 46th digit, and `digamma` at a
/// 33-digit rational next to `x₀` from its 5th; `πx` was rounded before
/// `cot`, and poles were taken within `2^{−wp/2}`.
fn arb_digamma(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || x.is_inf_pos() || x.is_inf_neg() {
        return Err(SymplexError::Unevaluable {
            reason: "Digamma of special float value".into(),
        });
    }
    let cap = cancellation_cap(prec);
    let mut extra = 20;
    loop {
        let wp = prec + extra;
        let (value, largest) = digamma_wp(x, wp, rm, cc)?;
        let lost = match (largest.exponent(), value.exponent()) {
            _ if value.is_zero() => wp,
            (Some(l), Some(v)) => usize::try_from(i64::from(l) - i64::from(v)).unwrap_or(0),
            _ => 0,
        };
        if lost + 16 <= extra {
            return Ok(round_to(value, prec, rm));
        }
        if extra >= cap {
            return Err(special_exhausted(prec));
        }
        extra = (lost + 32).max(2 * extra).min(cap);
    }
}

/// `ψ(x)` at working precision `wp` (see [`arb_digamma`]), with the
/// magnitude of the largest term summed: the absolute error is about
/// `2^−wp` of it.
fn digamma_wp(
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, BigFloat), SymplexError> {
    let pole = || SymplexError::Unevaluable {
        reason: "Digamma at non-positive integer pole".into(),
    };
    let exact = x.mantissa_max_bit_len().unwrap_or(wp).max(wp) + 64;
    let one = BigFloat::from_i32(1, wp);
    if x.is_negative() {
        // x = n + d, n = round(x), |d| ≤ ½, both exact.
        let n = x.add(&BigFloat::from_f64(0.5, 64), exact, rm).floor();
        let d = x.sub(&n, exact, rm);
        if d.is_zero() {
            return Err(pole());
        }
        let pi = cc.pi(wp, rm).clone();
        let pi_d = pi.mul(&d, wp, rm);
        let pi_cot = pi.mul(
            &pi_d.cos(wp, rm, cc).div(&pi_d.sin(wp, rm, cc), wp, rm),
            wp,
            rm,
        );
        let one_minus_x = BigFloat::from_i32(1, 64).sub(x, exact, rm);
        let (psi, largest) = digamma_wp(&one_minus_x, wp, rm, cc)?;
        let value = psi.sub(&pi_cot, wp, rm);
        let largest = if pi_cot.abs() > largest {
            pi_cot.abs()
        } else {
            largest
        };
        return Ok((value, largest));
    }
    if x.is_zero() {
        return Err(pole());
    }
    // ψ(x) = ψ(y) − Σ_{k<N} 1/(x + k), y = x + N ≥ wp/3.
    let threshold = BigFloat::from_i32(i32::try_from(wp / 3).unwrap_or(i32::MAX).max(10), wp);
    let mut shift = BigFloat::new(wp);
    let mut y = x.clone();
    while bf_lt(&y, &threshold) {
        shift = shift.add(&one.div(&y, wp, rm), wp, rm);
        y = y.add(&one, exact, rm);
    }
    let ln_y = y.ln(wp, rm, cc);
    let largest = if shift > ln_y.abs() {
        shift.clone()
    } else {
        ln_y.abs()
    };
    let two = BigFloat::from_i32(2, wp);
    let mut result = ln_y
        .sub(&one.div(&y.mul(&two, wp, rm), wp, rm), wp, rm)
        .sub(&shift, wp, rm);
    let y2 = y.mul(&y, wp, rm);
    let mut y_pow = y2.clone();
    let floor = largest.exponent().map_or(i64::MIN / 2, i64::from) - wp as i64 - 2;
    let mut prev: Option<i32> = None;
    for k in 1..=wp {
        let b2k = bernoulli::even(k);
        let denom = y_pow.mul(&BigFloat::from_i128(2 * k as i128, wp), wp, rm);
        let term = ratio_to_bigfloat(&b2k, wp, rm).div(&denom, wp, rm);
        match term.exponent() {
            Some(te) if i64::from(te) < floor => break,
            Some(te) if prev.is_some_and(|p| te > p + 2) => break, // diverging
            Some(te) => prev = Some(te),
            None => {}
        }
        result = result.sub(&term, wp, rm);
        y_pow = y_pow.mul(&y2, wp, rm);
    }
    Ok((result, largest))
}

// ═══════════════════════════════════════════════════════════════════════════
// Arbitrary-precision Gamma via Stirling series
// ═══════════════════════════════════════════════════════════════════════════

/// Compute log Γ(z) for real z > 0 using the Stirling asymptotic series.
///
/// Algorithm:
/// 1. Argument reduction — shift z by integer r until z + r ≥ 0.5 · p.
/// 2. Stirling series:
///    log Γ(z) = (z − ½) ln(z) − z + ½ ln(2π) + Σ B₂ₖ / [2k(2k−1) z^{2k−1}].
/// 3. Undo shift:
///    log Γ(z) = log Γ(z + r) − ln Π_{i=0}^{r−1} (z + i).
///
/// The series' smallest term is about `e^{−2π(z+r)}`; at `z + r ≥ 0.5·p`
/// it is far below `2^{−p}` after about `0.2·p` terms (the Bernoulli
/// numbers `B₂ₖ`, exact rationals, dominate the cost: at `0.2·p` they took
/// `0.35·p` terms, and `Γ(1/3)` at 1,200 digits 20 s before 0.30).
fn stirling_log_gamma(
    z: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    tracing::debug!(prec, "stirling_log_gamma: entry");

    let guard = 20; // extra guard bits
    let wp = prec + guard;

    // Determine how far to shift z for convergence.
    let z_approx = bigfloat_to_f64(z, rm, cc)?;
    let threshold = ((wp as f64) * 0.5).ceil() as i64;
    let shift = if z_approx < threshold as f64 {
        (threshold - z_approx.floor() as i64).max(0) as usize
    } else {
        0
    };

    tracing::trace!(
        z_approx,
        threshold,
        shift,
        "stirling_log_gamma: argument reduction"
    );

    // z_shifted = z + shift
    let shift_bf = BigFloat::from_i128(shift as i128, wp);
    let z_shifted = z.add(&shift_bf, wp, rm);

    // Main Stirling formula:
    //   log Γ(z) = (z − 1/2)·ln(z) − z + (1/2)·ln(2π) + Σ ...
    let half = BigFloat::from_f64(0.5, wp);
    let z_minus_half = z_shifted.sub(&half, wp, rm);
    let log_z = z_shifted.ln(wp, rm, cc);

    let mut result = z_minus_half.mul(&log_z, wp, rm);
    result = result.sub(&z_shifted, wp, rm);

    // (1/2) · ln(2π) at working precision.
    let two = BigFloat::from_i32(2, wp);
    let pi_val = cc.pi(wp, rm).clone();
    let two_pi = two.mul(&pi_val, wp, rm);
    let half_log_2pi = two_pi.ln(wp, rm, cc).mul(&half, wp, rm);
    result = result.add(&half_log_2pi, wp, rm);

    // Series: Σ_{k=1}^{N} B_{2k} / [2k(2k−1) · z^{2k−1}]
    let z_sq = z_shifted.mul(&z_shifted, wp, rm);
    let mut z_pow = z_shifted.clone(); // z^1 → z^3 → z^5 → …

    // Upper bound on useful terms: safely below the divergence point πz.
    let max_terms = ((wp as f64) * 0.35) as usize + 10;
    let mut prev_term_exp: Option<i32> = None;

    for k in 1..=max_terms {
        let b2k = bernoulli::even(k);
        if b2k.is_zero() {
            continue;
        }

        // Advance z_pow: z^1, z^3, z^5, …
        if k > 1 {
            z_pow = z_pow.mul(&z_sq, wp, rm);
        }

        // term = B_{2k} / (2k · (2k−1) · z^{2k−1})
        let b2k_bf = ratio_to_bigfloat(&b2k, wp, rm);
        let denom_int = (2 * k * (2 * k - 1)) as i128;
        let denom = BigFloat::from_i128(denom_int, wp);
        let denom_full = denom.mul(&z_pow, wp, rm);
        let term = b2k_bf.div(&denom_full, wp, rm);

        // Divergence / convergence detection via binary exponents.
        if let Some(t_exp) = term.exponent() {
            if let Some(prev) = prev_term_exp
                && t_exp > prev + 10
            {
                tracing::trace!(k, "stirling series: diverging, stopping");
                break;
            }
            prev_term_exp = Some(t_exp);

            // Term is negligible relative to accumulated result.
            if let Some(r_exp) = result.exponent()
                && (r_exp as i64 - t_exp as i64) > wp as i64
            {
                tracing::trace!(k, "stirling series: converged");
                break;
            }
        }

        result = result.add(&term, wp, rm);
    }

    // Undo argument reduction:
    //   log Γ(z) = log Γ(z+shift) − ln Π_{i=0}^{shift−1} (z + i),
    // one logarithm of the product instead of one per factor (850
    // logarithms at 4,000 bits took a second).  The product carries the
    // roundings of its factors, `shift·2^−wp` relative, as the sum of
    // logarithms did.
    if shift > 0 {
        let mut product = BigFloat::from_i32(1, wp);
        for i in 0..shift {
            let z_plus_i = z.add(&BigFloat::from_i128(i as i128, wp), wp, rm);
            product = product.mul(&z_plus_i, wp, rm);
        }
        result = result.sub(&product.ln(wp, rm, cc), wp, rm);
    }

    Ok(result)
}

/// Compute Γ(x) at arbitrary precision for real x.
///
/// For positive x, evaluates exp(stirling_log_gamma(x)).
/// For negative non-integer x, applies the reflection formula
/// Γ(z) = π / (sin(πd) · (−1)ⁿ · Γ(1 − z)) with `z = n + d`, `n = round(z)`
/// and `d` exact, so that `sin` is accurate next to a pole (before 0.29 `πz`
/// was rounded first, losing `log₂(1/d)` bits, and arguments within
/// `10⁻¹²` of a pole — in `f64` — or `2^{−prec/2}` were refused as poles).
fn arb_gamma_real(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    // The poles: the non-positive integers, exactly.
    if x.is_zero() || (x.is_negative() && x.is_int()) {
        return Err(SymplexError::Unevaluable {
            reason: "Gamma at non-positive integer pole".into(),
        });
    }

    if !x.is_negative() {
        // Direct Stirling path.
        tracing::debug!(prec, "arb_gamma_real: positive argument");
        let log_gamma = stirling_log_gamma(x, prec, rm, cc)?;
        Ok(log_gamma.exp(prec, rm, cc))
    } else {
        tracing::debug!(prec, "arb_gamma_real: reflection formula");
        let exact = x.mantissa_max_bit_len().unwrap_or(prec).max(prec) + 64;
        let one_minus_x = BigFloat::from_i32(1, 64).sub(x, exact, rm);
        let log_gamma_1mx = stirling_log_gamma(&one_minus_x, prec, rm, cc)?;
        let gamma_1mx = log_gamma_1mx.exp(prec, rm, cc);

        // sin(πz) = (−1)ⁿ sin(πd).
        let n = x.add(&BigFloat::from_f64(0.5, 64), exact, rm).floor();
        let d = x.sub(&n, exact, rm);
        let pi_val = cc.pi(prec, rm).clone();
        let mut sin_pi_x = pi_val.mul(&d, prec, rm).sin(prec, rm, cc);
        let odd = !n
            .div(&BigFloat::from_i32(2, 64), exact, rm)
            .fract()
            .is_zero();
        if odd {
            sin_pi_x = sin_pi_x.neg();
        }
        if sin_pi_x.is_zero() {
            return Err(SymplexError::Unevaluable {
                reason: "Gamma at non-positive integer pole".into(),
            });
        }

        let denom = sin_pi_x.mul(&gamma_1mx, prec, rm);
        Ok(pi_val.div(&denom, prec, rm))
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Arbitrary-precision erf via Taylor series / asymptotic expansion
// ═══════════════════════════════════════════════════════════════════════════

/// `erfc(x)` for `x > 0` from the asymptotic expansion
///
/// ```text
/// erfc(x) = exp(−x²)/(x√π) · Σ_{n≥0} (−1)^n (2n−1)!! / (2x²)^n
/// ```
///
/// truncated at its smallest term (near `n ≈ x²`), so the *relative* error
/// is `≈ e^{−x²}`: callers must ensure `x² ≳ wp·ln 2` when they need
/// `erfc` itself to `wp` bits, or `2x² ≳ wp·ln 2` when they only need
/// `erf = 1 − erfc` to `wp` bits (the absolute error is then `≈ e^{−2x²}`).
fn erfc_asymptotic(ax: &BigFloat, wp: usize, rm: RoundingMode, cc: &mut Consts) -> BigFloat {
    let x_sq = ax.mul(ax, wp, rm);
    let (sum, x_sqrt_pi) = erfc_asymptotic_series(ax, wp, rm, cc);
    let exp_neg_x_sq = x_sq.neg().exp(wp, rm, cc);
    exp_neg_x_sq.mul(&sum, wp, rm).div(&x_sqrt_pi, wp, rm)
}

/// The sum `Σ_{n≥0} (−1)^n (2n−1)!!/(2x²)^n` of [`erfc_asymptotic`] at `wp`
/// bits, truncated at its smallest term, and `x·√π`: `erfc(x)` is
/// `e^(−x²)·sum/(x√π)` (`extended` takes `e^(−x²)` at its own scale, below
/// the exponent range).
fn erfc_asymptotic_series(
    ax: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> (BigFloat, BigFloat) {
    let x_sq = ax.mul(ax, wp, rm);
    let two_x_sq = x_sq.mul(&BigFloat::from_i32(2, wp), wp, rm);

    let mut sum = BigFloat::from_i32(1, wp);
    let mut term = BigFloat::from_i32(1, wp);
    let mut prev_abs: Option<BigFloat> = None;
    // The terms shrink until `n ≈ x²`; past that they grow and the loop
    // stops, so `wp + 40` is only reached when the terms are already tiny.
    let max_terms = wp + 40;
    for n in 1..=max_terms {
        // term *= −(2n−1) / (2x²)
        let factor = BigFloat::from_i128(2 * n as i128 - 1, wp);
        term = term.mul(&factor, wp, rm).div(&two_x_sq, wp, rm).neg();
        let t_abs = term.abs();
        if let Some(ref p) = prev_abs
            && bf_gt(&t_abs, p)
        {
            break; // past the smallest term: optimal truncation
        }
        sum = sum.add(&term, wp, rm);
        if negligible(&term, &sum, wp) {
            break;
        }
        prev_abs = Some(t_abs);
    }

    let sqrt_pi = cc.pi(wp, rm).clone().sqrt(wp, rm);
    let x_sqrt_pi = ax.mul(&sqrt_pi, wp, rm);
    (sum, x_sqrt_pi)
}

/// Compute erf(x) at arbitrary precision for real x.  The result carries
/// `prec + 32` bits.
///
/// For small-to-moderate |x|, uses the Taylor series:
///   erf(x) = (2/√π) Σ_{n=0}^{N} (-1)^n x^{2n+1} / (n! (2n+1))
/// whose terms peak near `n ≈ x²` at `≈ e^{x²}` before the alternating sum
/// cancels down to `|erf| < 1`, so the working precision carries
/// `x² log₂ e` extra bits.
///
/// For large |x| (`2x² ≳ wp·ln 2`), uses [`erfc_asymptotic`]:
///   erf(x) = sign(x) · (1 − erfc(|x|))
fn arb_erf(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_zero() {
        return Ok(BigFloat::new(prec));
    }

    let guard = 32;
    let wp = prec + guard;

    let x_approx = bigfloat_to_f64(x, rm, cc)?;
    // Threshold: for |x| beyond this, the asymptotic expansion (absolute
    // error ≈ e^{−2x²} for erf) is accurate to wp bits. Roughly √(wp·ln 2/2).
    let threshold = ((wp as f64) * 0.35).sqrt() + 2.0;

    if x_approx.abs() < threshold {
        // ── Taylor series ──────────────────────────────────────────────────────────
        // erf(x) = (2/√π) · Σ_{n=0}^{N} prod_n / (2n+1)
        // where prod_0 = x, prod_{n+1} = prod_n · (-x²) / (n+1)
        let x_sq_f = x_approx * x_approx;
        let cancel = (x_sq_f * std::f64::consts::LOG2_E).ceil() as usize + 8;
        let wpt = wp + cancel;
        let mut xw = x.clone();
        let _ = xw.set_precision(wpt, rm);
        let neg_x_sq = xw.mul(&xw, wpt, rm).neg();
        let mut prod = xw.clone(); // (-x²)^n · x / n!
        let mut sum = xw.clone(); // accumulator (first term = x)

        // |term_n| < 2^{−wpt} needs n ≈ 5x² at the threshold, fewer below it.
        let max_terms = (6.0 * x_sq_f) as usize + wpt + 60;
        let mut converged = false;
        for n in 1..=max_terms {
            // prod *= -x² / n
            prod = prod.mul(&neg_x_sq, wpt, rm);
            prod = prod.div(&BigFloat::from_i128(n as i128, wpt), wpt, rm);

            // term = prod / (2n+1)
            let divisor = BigFloat::from_i128(2 * n as i128 + 1, wpt);
            let term = prod.div(&divisor, wpt, rm);

            if negligible(&term, &sum, wpt) {
                converged = true;
                break;
            }
            sum = sum.add(&term, wpt, rm);
        }
        if !converged {
            return Err(series_did_not_converge("erf", max_terms));
        }

        // Multiply by 2/√π
        let two = BigFloat::from_i32(2, wpt);
        let pi_val = cc.pi(wpt, rm).clone();
        let sqrt_pi = pi_val.sqrt(wpt, rm);
        let two_over_sqrt_pi = two.div(&sqrt_pi, wpt, rm);

        Ok(round_to(sum.mul(&two_over_sqrt_pi, wpt, rm), wp, rm))
    } else {
        // ── Asymptotic expansion for large |x| ────────────────────────────────────
        let mut ax = x.abs();
        let _ = ax.set_precision(wp, rm);
        let erfc_val = erfc_asymptotic(&ax, wp, rm, cc);
        let one = BigFloat::from_i32(1, wp);
        let erf_val = one.sub(&erfc_val, wp, rm);

        if x.is_negative() {
            Ok(erf_val.neg())
        } else {
            Ok(erf_val)
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Helpers
// ═══════════════════════════════════════════════════════════════════════════

// ═══════════════════════════════════════════════════════════════════════════
// Euler-Mascheroni constant at arbitrary precision (Brent-McMillan B1)
// ═══════════════════════════════════════════════════════════════════════════

/// Compute the Euler-Mascheroni constant γ at `prec` bits of precision
/// using the Brent-McMillan B1 algorithm.
///
/// This is the fastest known algorithm for computing γ.  It uses the identity
/// involving modified Bessel functions, simplified to a fixed-point summation
/// with convergence rate O(e^{-4n}) where n = 2^p.
///
/// Reference: Brent & McMillan (1980), mpmath `euler_fixed`.
fn arb_euler_gamma(
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    // We need ln(2) at working precision.
    let extra = 30;
    let wp = prec + extra;

    // Choose p such that e^{-4·2^p} < 2^{-wp}, i.e. 4·2^p > wp·ln(2),
    // i.e. p > log2(wp·ln(2)/4).
    let p = ((wp as f64 / 4.0) * std::f64::consts::LN_2).log2().ceil() as u64 + 1;
    let n: i128 = 1i128 << p;
    let n_sq = n * n;

    // ln(2) at working precision.
    let two_bf = BigFloat::from_i32(2, wp);
    let ln2 = two_bf.ln(wp, rm, cc);

    // A = U = -p · ln(2)   (= -ln(n) since n = 2^p)
    let p_bf = BigFloat::from_i128(p as i128, wp);
    let neg_p_ln2 = p_bf.mul(&ln2, wp, rm).neg();

    let mut a = neg_p_ln2.clone();
    let mut u = neg_p_ln2;
    // B = V = 1
    let one = BigFloat::from_i32(1, wp);
    let mut b = one.clone();
    let mut v = one.clone();

    let n_sq_bf = BigFloat::from_i128(n_sq, wp);

    let mut k: i128 = 1;
    loop {
        let k_bf = BigFloat::from_i128(k, wp);
        let k_sq_bf = k_bf.mul(&k_bf, wp, rm);

        // B = B · n² / k²
        b = b.mul(&n_sq_bf, wp, rm).div(&k_sq_bf, wp, rm);

        // A = (A · n² / k + B) / k
        a = a.mul(&n_sq_bf, wp, rm).div(&k_bf, wp, rm);
        a = a.add(&b, wp, rm).div(&k_bf, wp, rm);

        u = u.add(&a, wp, rm);
        v = v.add(&b, wp, rm);

        // Convergence: both A and B are negligibly small.
        let a_small = a.exponent().is_none_or(|e| e < -(wp as i32) + 10);
        let b_small = b.exponent().is_none_or(|e| e < -(wp as i32) + 10);
        if a_small && b_small {
            tracing::trace!(k, "arb_euler_gamma: converged");
            break;
        }

        k += 1;
        if k > 10 * (wp as i128) {
            return Err(SymplexError::ComputationFailed {
                operation: "euler_gamma",
                reason: "Brent-McMillan did not converge".into(),
            });
        }
    }

    // γ = U / V
    Ok(u.div(&v, prec, rm))
}

// ═══════════════════════════════════════════════════════════════════════════
// Hankel P/Q series for Bessel asymptotic expansion
// ═══════════════════════════════════════════════════════════════════════════

/// Compute the Hankel auxiliary functions P_ν(z) and Q_ν(z) for the
/// Bessel asymptotic expansion (DLMF §10.17).
///
/// P_ν(z) = Σ_{k=0}^{N} (-1)^k · a_{2k}(ν) / z^{2k}
/// Q_ν(z) = Σ_{k=0}^{N} (-1)^k · a_{2k+1}(ν) / z^{2k+1}
///
/// where a_k(ν) = (4ν²−1²)(4ν²−3²)⋯(4ν²−(2k−1)²) / (k! · 8^k)
/// (DLMF 10.17.1), so a_k = a_{k−1} · (4ν² − (2k−1)²) / (8k).
///
/// Uses optimal truncation: stops when terms start increasing (divergent
/// series).  The error is bounded by the first omitted term for real
/// positive z (DLMF §10.17(iii)).  The returned flag is `true` when the
/// truncation happened because the terms fell below `2^{-prec}` relative
/// to the sums — i.e. the expansion actually delivered `prec` bits.  When
/// it is `false` the series started diverging before reaching the target
/// and the caller must fall back to the power series.
fn hankel_pq(
    order: &BigFloat,
    z: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    _cc: &mut Consts,
) -> (BigFloat, BigFloat, bool) {
    let one = BigFloat::from_i32(1, prec);
    let four = BigFloat::from_i32(4, prec);
    let eight = BigFloat::from_i32(8, prec);

    let four_nu_sq = four.mul(&order.mul(order, prec, rm), prec, rm);

    let z_inv = one.div(z, prec, rm);

    // P and Q accumulators; the k = 0 term (a_0 = 1) is added by the loop.
    let mut p_sum = BigFloat::new(prec);
    let mut q_sum = BigFloat::new(prec);

    let mut a_k = one.clone(); // a_0 = 1
    let mut z_power = one.clone(); // z^0 = 1

    // The terms reach their minimum near k ≈ 2|z|; allow a little slack.
    let max_terms = (3 * prec + 100).min(100_000);

    let mut prev_a_abs: Option<BigFloat> = None;
    let mut converged = false;

    for k in 0..max_terms {
        if k > 0 {
            // a_k = a_{k-1} · (4ν² - (2k-1)²) / (8k)
            let two_km1 = BigFloat::from_i32((2 * k as i32) - 1, prec);
            let two_km1_sq = two_km1.mul(&two_km1, prec, rm);
            let numer = four_nu_sq.sub(&two_km1_sq, prec, rm);
            let k_bf = BigFloat::from_i32(k as i32, prec);
            let denom = eight.mul(&k_bf, prec, rm);
            a_k = a_k.mul(&numer, prec, rm).div(&denom, prec, rm);
            // A half-integer order ends the expansion: `4ν² = (2k−1)²`
            // exactly, and every later coefficient has the factor 0 — the
            // sums are complete (spherical Bessel functions).  Before 0.30
            // the zero terms never met the convergence test, the expansion
            // was reported as failing, and the power series took over
            // with `1.44·x` guard bits: `besselj(5/2, 10²⁵)` printed
            // `3.8·10¹⁰⁵²⁷`, `besselj(−3/2, 12!)` hung.
            if a_k.is_zero() {
                converged = true;
                break;
            }

            // Update z_power: multiply by 1/z each step.
            z_power = z_power.mul(&z_inv, prec, rm);
        }

        // term = a_k / z^k
        let term = a_k.mul(&z_power, prec, rm);

        // Check for divergence: if |term| > |prev_term|, stop.
        let term_abs = term.abs();
        if let Some(ref prev) = prev_a_abs
            && term_abs.partial_cmp(prev) == Some(std::cmp::Ordering::Greater)
            && k > 2
        {
            tracing::trace!(k, "hankel_pq: optimal truncation (terms diverging)");
            break;
        }

        // Convergence: term negligible relative to accumulated sums.
        let p_exp = p_sum.exponent().unwrap_or(0);
        let q_exp = q_sum.exponent().unwrap_or(0);
        let ref_exp = p_exp.max(q_exp);
        let t_exp = term.exponent().unwrap_or(i32::MIN / 2);
        if k > 0 && (ref_exp as i64 - t_exp as i64) > prec as i64 {
            tracing::trace!(k, "hankel_pq: converged (term negligible)");
            converged = true;
            break;
        }

        prev_a_abs = Some(term_abs);

        // Even k → contributes to P with sign (-1)^(k/2)
        // Odd k → contributes to Q with sign (-1)^((k-1)/2)
        if k % 2 == 0 {
            // P term: (-1)^(k/2) · a_k / z^k
            if (k / 2) % 2 == 0 {
                p_sum = p_sum.add(&term, prec, rm);
            } else {
                p_sum = p_sum.sub(&term, prec, rm);
            }
        } else {
            // Q term: (-1)^((k-1)/2) · a_k / z^k
            if ((k - 1) / 2) % 2 == 0 {
                q_sum = q_sum.add(&term, prec, rm);
            } else {
                q_sum = q_sum.sub(&term, prec, rm);
            }
        }
    }

    (p_sum, q_sum, converged)
}

/// Smallest `|x|` at which the Hankel expansion is expected to reach `wp`
/// bits for order `ν`.
///
/// The smallest term of the (divergent) expansion is `~e^{−2|x|}` times a
/// factor that grows like `e^{2|ν|}` (the first `|ν|` coefficients are
/// inflated by `4ν²/(2j−1)²`), so `2|x| ≳ (wp + 3|ν|)·ln 2`.  This is
/// only a heuristic for choosing the algorithm; [`hankel_pq`] reports
/// whether it actually converged.
fn hankel_threshold(wp: usize, order_abs: f64) -> f64 {
    (wp as f64 + 3.0 * order_abs) * std::f64::consts::LN_2 / 2.0 + 4.0
}

/// Evaluate `J_ν(x)` (`want_j == true`) or `Y_ν(x)` via the Hankel
/// asymptotic expansion at `x > 0`,
///
/// ```text
/// J_ν(x) = √(2/(πx)) · [cos(ω)·P_ν(x) − sin(ω)·Q_ν(x)]
/// Y_ν(x) = √(2/(πx)) · [sin(ω)·P_ν(x) + cos(ω)·Q_ν(x)],   ω = x − νπ/2 − π/4
/// ```
///
/// Returns `None` when the expansion does not reach `wp` bits at this
/// `x` (the caller then uses the power series).
fn bessel_jy_hankel(
    order: &BigFloat,
    x: &BigFloat,
    want_j: bool,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Option<BigFloat> {
    // The phase ω = x − νπ/2 − π/4 loses the leading `log2 x` bits of x to
    // cancellation, so the trigonometric part needs that many extra bits
    // (the caller refuses beyond `cancellation_cap`).
    let wp = wp + x.exponent().unwrap_or(0).max(0) as usize;
    let mut xw = x.clone();
    let _ = xw.set_precision(wp, rm);
    let mut nu = order.clone();
    let _ = nu.set_precision(wp, rm);

    let (p_val, q_val, converged) = hankel_pq(&nu, &xw, wp, rm, cc);
    if !converged {
        tracing::trace!("bessel_jy_hankel: expansion did not reach target precision");
        return None;
    }
    let pi = cc.pi(wp, rm).clone();
    let two = BigFloat::from_i32(2, wp);
    let four = BigFloat::from_i32(4, wp);

    let two_over_pi_x = two.div(&pi.mul(&xw, wp, rm), wp, rm);
    let amplitude = two_over_pi_x.sqrt(wp, rm);

    let nu_pi_half = nu.mul(&pi, wp, rm).div(&two, wp, rm);
    let pi_quarter = pi.div(&four, wp, rm);
    let phase = xw.sub(&nu_pi_half, wp, rm).sub(&pi_quarter, wp, rm);

    let cos_phase = phase.cos(wp, rm, cc);
    let sin_phase = phase.sin(wp, rm, cc);

    let combo = if want_j {
        cos_phase
            .mul(&p_val, wp, rm)
            .sub(&sin_phase.mul(&q_val, wp, rm), wp, rm)
    } else {
        sin_phase
            .mul(&p_val, wp, rm)
            .add(&cos_phase.mul(&q_val, wp, rm), wp, rm)
    };
    Some(amplitude.mul(&combo, wp, rm))
}

// ═══════════════════════════════════════════════════════════════════════════
// Bessel function evaluation (arbitrary precision)
// ═══════════════════════════════════════════════════════════════════════════

/// Arbitrary-precision Bessel function of the first kind J_ν(x).
///
/// * `|x|` below [`hankel_threshold`] (or whenever the asymptotic expansion
///   cannot reach the target precision): ascending power series
///   `J_ν(x) = Σ_k (-1)^k (x/2)^(ν+2k) / (k! Γ(ν+k+1))`.  Its terms grow
///   to `~e^{|x|}` before the alternating sum cancels down to `O(1)`, so
///   the working precision is raised by [`cancellation_guard_bits`] — this
///   makes the series correct at *any* `x`, merely slower for huge `x`.
/// * Otherwise the Hankel expansion with the full `P/Q` series
///   ([`bessel_jy_hankel`]), whose optimal-truncation error is `~e^{−2|x|}`.
fn arb_bessel_j(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let classic = arb_bessel_j_classic(order, x, prec, rm, cc);
    debye_fallback(bessel_debye::Kind::J, order, x, prec, rm, cc, classic)
}

/// Where the series and the Hankel expansion of the Bessel functions give
/// up (`classic` is an error), the uniform expansions of large order
/// (`bessel_debye`), at `abs(ν)` for `K_ν` and for the integer orders of
/// `I_ν` (`I_{−n} = I_n`) and at `abs(x)` for an integer order of `J_ν` and
/// `I_ν` (`f_n(−x) = (−1)ⁿ f_n(x)`); the error stands where they do not
/// apply.  Before 0.35 `bessely(20000, 300)`, `besselk(20000, 300)`,
/// `bessely(20000, 30000)`, `besseli(1000, 120000)` and `besselj(20000,
/// 19000)` were refused.
fn debye_fallback(
    kind: bessel_debye::Kind,
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
    classic: Result<BigFloat, SymplexError>,
) -> Result<BigFloat, SymplexError> {
    use bessel_debye::Kind;
    let Err(err) = classic else {
        return classic;
    };
    let integer = order.is_int();
    let negative_x = x.is_negative();
    // `J_{−ν}`, `Y_{−ν}` of a non-integer order from `J_ν` and `Y_ν`.
    if order.is_negative()
        && !integer
        && matches!(kind, Kind::J | Kind::Y)
        && !negative_x
        && let Some(v) = bessel_reflected(kind, &order.abs(), x, prec, rm, cc)
    {
        return v;
    }
    let nu = match kind {
        Kind::K => order.abs(),
        Kind::I if integer => order.abs(),
        _ if order.is_negative() => return Err(err),
        _ => order.clone(),
    };
    if negative_x && !(integer && matches!(kind, Kind::J | Kind::I)) {
        return Err(err);
    }
    match bessel_jy_large(kind, &nu, &x.abs(), prec, rm, cc) {
        Some(Ok(v)) if negative_x && bessel_order::is_odd(order) => Ok(v.neg()),
        Some(r) => r,
        None => Err(err),
    }
}

/// A Bessel function of large positive order `nu` at `x > 0` by the uniform
/// expansions (`bessel_debye`), and for `J`, `Y` where they stop short — the
/// turning point `x ≈ ν`, `Y_ν(x)` for `x < ν` — by the recurrence in the
/// order from where they do not (`bessel_recur`).  Before 0.37
/// `besselj(20000, 20000)`, `bessely(20000, 20100)` and `bessely(20000,
/// 14800)` were refused.
fn bessel_jy_large(
    kind: bessel_debye::Kind,
    nu: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Option<Result<BigFloat, SymplexError>> {
    use bessel_debye::Kind;
    match bessel_debye::debye(kind, nu, x, prec, rm, cc) {
        Some(r) => Some(r),
        None if matches!(kind, Kind::J | Kind::Y) => bessel_recur::recur(kind, nu, x, prec, rm, cc),
        None => None,
    }
}

/// `J_{−ν}(x) = cos(νπ)·J_ν(x) − sin(νπ)·Y_ν(x)` and
/// `Y_{−ν}(x) = sin(νπ)·J_ν(x) + cos(νπ)·Y_ν(x)` (DLMF 10.4.7, 10.4.8)
/// for a non-integer `ν > 0` and `x > 0`, `J_ν` and `Y_ν` by
/// [`bessel_jy_large`] (`None` where they are not available).  `νπ` is reduced exactly: `ν = n + f` with an integer `n`, the
/// signs `(−1)ⁿ`.  The cancellation of the two terms is measured and made up
/// with more bits.  Before 0.37 `besselj(−(1000 + 1/3), 2000)` was refused.
fn bessel_reflected(
    kind: bessel_debye::Kind,
    nu: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Option<Result<BigFloat, SymplexError>> {
    use bessel_debye::Kind;
    let mut wp = prec + 32;
    let cap = 4 * prec + 1024;
    loop {
        let j = match bessel_jy_large(Kind::J, nu, x, wp, rm, cc)? {
            Ok(v) => v,
            Err(e) => return Some(Err(e)),
        };
        let y = match bessel_jy_large(Kind::Y, nu, x, wp, rm, cc)? {
            Ok(v) => v,
            Err(e) => return Some(Err(e)),
        };
        // ν = n + f, 0 < f < 1: cos(νπ) = (−1)ⁿ cos(fπ), sin(νπ) = (−1)ⁿ sin(fπ).
        let n = nu.floor();
        let f = nu.sub(&n, exact_bits(nu, wp), rm);
        let pi = cc.pi(wp + 16, rm).clone();
        let angle = f.mul(&pi, wp + 16, rm);
        let odd = bessel_order::is_odd(&n);
        let sign = |v: BigFloat| if odd { v.neg() } else { v };
        let (c, s) = (sign(angle.cos(wp, rm, cc)), sign(angle.sin(wp, rm, cc)));
        let (a, b) = match kind {
            Kind::J => (c.mul(&j, wp, rm), s.mul(&y, wp, rm).neg()),
            _ => (s.mul(&j, wp, rm), c.mul(&y, wp, rm)),
        };
        let v = a.add(&b, wp, rm);
        // The error is at most `2^(2 − wp)·(abs(J) + abs(Y))` (`J`, `Y` to
        // `2^(−wp)` relative, the sine and cosine to `2^(1 − wp)` absolute, the
        // products) and `2^(−wp)·abs(v)`: the bits lost against the larger
        // of `J`, `Y`.
        let big = j
            .exponent()
            .unwrap_or(i32::MIN / 2)
            .max(y.exponent().unwrap_or(i32::MIN / 2));
        let lost = if v.is_zero() {
            wp as i64
        } else {
            i64::from(big) - i64::from(v.exponent().unwrap_or(i32::MIN / 2)) + 1
        };
        if lost + 6 + (prec as i64) <= wp as i64 {
            return Some(Ok(round_to(v, prec, rm)));
        }
        if wp >= cap {
            return None;
        }
        wp = (wp + lost.max(32) as usize).min(cap);
    }
}

/// [`arb_bessel_j`] by the ascending series and the Hankel expansion.
fn arb_bessel_j_classic(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let guard = 32;
    let wp = prec + guard;

    // Special case: x = 0.
    if x.is_zero() {
        let order_f64 = bigfloat_to_f64(order, rm, cc)?;
        return if order_f64.abs() < 1e-15 {
            // J_0(0) = 1
            Ok(BigFloat::from_i32(1, prec))
        } else if order_f64 > 0.0 {
            // J_n(0) = 0 for n > 0
            Ok(BigFloat::new(prec))
        } else {
            Err(SymplexError::Unevaluable {
                reason: "BesselJ at x=0 with negative order".into(),
            })
        };
    }

    refuse_bessel_argument(x, prec)?;
    // `(x/2)^ν` of a negative `x` is complex for a non-integer order.
    // Before 0.30 the power series took `|x/2|^ν` and returned a real
    // number: `besselj(−1/2, −1)` was `0.431…`, truly `−0.431…·i`.
    if x.is_negative() && !order.is_int() {
        return Err(SymplexError::Unevaluable {
            reason: "BesselJ of negative argument with non-integer order is complex".into(),
        });
    }
    let x_f64 = bigfloat_to_f64(x, rm, cc)?;
    let order_f64 = bigfloat_to_f64(order, rm, cc)?;

    // Check for integer order (most common case) — exactly: before 0.29 an
    // order within 10⁻¹² of an integer was taken for it, and
    // `besselj(2 + 10⁻¹⁴, 1)` was wrong from its 15th digit.
    let order_int = order_f64.round() as i64;
    let is_int_order = order.is_int();
    let large = order_f64.abs() >= bessel_order::LARGE_ORDER;

    // Negative integer order: J_{-n}(x) = (-1)^n J_n(x) — the order negated
    // and its parity taken exactly (before 0.34 through an `i64`, which
    // saturates beyond 9.2·10¹⁸: `besselj(−10²⁰, x)` recursed without end).
    if is_int_order && order.is_negative() {
        let j = arb_bessel_j(&order.neg(), x, prec, rm, cc)?;
        return Ok(if bessel_order::is_odd(order) {
            j.neg()
        } else {
            j
        });
    }

    // Large |x|: Hankel asymptotic expansion (J is even/odd in x for
    // integer order; non-integer order with x < 0 is complex and rejected).
    if x_f64.abs() >= hankel_threshold(wp, order_f64.abs()) {
        if x.is_negative() {
            if !is_int_order {
                return Err(SymplexError::Unevaluable {
                    reason: "BesselJ of negative argument with non-integer order is complex".into(),
                });
            }
            let j = arb_bessel_j(order, &x.abs(), prec, rm, cc)?;
            return Ok(if bessel_order::is_odd(order) {
                j.neg()
            } else {
                j
            });
        }
        if let Some(j) = bessel_jy_hankel(order, x, true, wp, rm, cc) {
            return Ok(round_to(j, prec, rm));
        }
    }

    // ── Ascending series with cancellation guard bits ──────────────────
    // J_ν(x) = (x/2)^ν · Σ_{k=0}^N (-1)^k · (x/2)^{2k} / (k! · Γ(ν+k+1))
    {
        let wp = wp + series_guard_bits(x_f64.abs(), prec)?;
        let mut xw = x.clone();
        let _ = xw.set_precision(wp, rm);
        let mut order_w = order.clone();
        let _ = order_w.set_precision(wp, rm);
        let order = &order_w;
        let two = BigFloat::from_i32(2, wp);
        let x_half = xw.div(&two, wp, rm);
        let x_half_sq = x_half.mul(&x_half, wp, rm);
        let neg_x_half_sq = x_half_sq.neg();

        // Series: sum = Σ (-1)^k · (x/2)^{2k} / (k! · Γ(ν+k+1))
        // We track term = (-x²/4)^k / (k! · Γ(ν+k+1)) incrementally.
        // term_{k+1} = term_k · (-x²/4) / ((k+1) · (ν+k+1))
        let mut sum = BigFloat::new(wp); // will add 1/Γ(ν+1) as first term

        // A large order: the factor (x/2)^ν/Γ(ν+1) at once, its exponent
        // to an absolute 2^(−wp) (`bessel_order`), and the series from 1.
        // Before 0.34 an integer order took a multiplication per unit:
        // `besselj(8345185991999992, 61/10²⁷)` never finished.
        let (prefix, mut term) = if large {
            let bounds = bessel_order::series_bounds(order_f64, x_f64.abs(), true);
            // Below the range (only for `0 < abs(x) < ν`): 0, which the
            // accuracy layer holds as the underflow of a nonzero `J_ν`
            // (`J_ν` has no zero there, `accuracy::underflowed`) and
            // `extended` scales.  Before 0.34 `besselj(10⁸ + 1/2, 1)`
            // printed `0`; in 0.34 it was refused where it arose, and so was
            // `1 + besselj(10⁹, 1)`.
            let Some(p) = bessel_order::power_over_gamma(
                order,
                &x_half.abs(),
                bounds,
                "besselj",
                wp,
                rm,
                cc,
            )?
            else {
                return Ok(BigFloat::new(prec));
            };
            // J_n(−x) = (−1)ⁿ J_n(x) (a negative x has an integer order here).
            let p = if x.is_negative() && bessel_order::is_odd(order) {
                p.neg()
            } else {
                p
            };
            (p, BigFloat::from_i32(1, wp))
        } else {
            // Compute (x/2)^ν.  For integer order, use repeated multiplication.
            let prefix = if is_int_order && order_int >= 0 {
                let mut p = BigFloat::from_i32(1, wp);
                for _ in 0..order_int {
                    p = p.mul(&x_half, wp, rm);
                }
                p
            } else {
                // General: (x/2)^ν = exp(ν · ln(x/2))
                let ln_xh = x_half.abs().ln(wp, rm, cc);
                let nu_ln = order.mul(&ln_xh, wp, rm);
                nu_ln.exp(wp, rm, cc)
            };
            // First term (k=0): 1 / Γ(ν+1)
            let gamma_nu1 =
                arb_gamma_real(&order.add(&BigFloat::from_i32(1, wp), wp, rm), wp, rm, cc)?;
            (prefix, BigFloat::from_i32(1, wp).div(&gamma_nu1, wp, rm))
        };
        sum = sum.add(&term, wp, rm);

        // The terms peak near k ≈ |x|/2 and then decay super-exponentially;
        // `|x| + wp` comfortably covers the tail down to 2^{-wp}.
        let max_terms = (x_f64.abs() * 1.5) as usize + wp + 40;
        for k in 1..=max_terms {
            // term *= (-x²/4) / (k · (ν + k))
            let k_bf = BigFloat::from_i32(k as i32, wp);
            let nu_plus_k = order.add(&k_bf, wp, rm);
            let denom = k_bf.mul(&nu_plus_k, wp, rm);
            term = term.mul(&neg_x_half_sq, wp, rm);
            term = term.div(&denom, wp, rm);

            // Convergence check (only once past the peak of the terms).
            if (k as f64) > x_f64.abs() / 2.0
                && let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
                && (s_exp as i64 - t_exp as i64) > wp as i64
            {
                tracing::trace!(k, "arb_bessel_j: series converged");
                break;
            }

            sum = sum.add(&term, wp, rm);
        }

        let r = prefix.mul(&sum, wp, rm);
        if large && (r.is_zero() || r.is_inf()) {
            return Err(SymplexError::Unevaluable {
                reason: "besselj of large order: the value leaves the arbitrary-precision \
                         exponent range"
                    .into(),
            });
        }
        Ok(round_to(r, prec, rm))
    }
}

/// Arbitrary-precision Bessel function of the second kind Y_ν(x), `x > 0`.
///
/// * Large `x` (see [`hankel_threshold`]): Hankel expansion
///   ([`bessel_jy_hankel`]), falling back to the series if it cannot reach
///   the target precision.
/// * Otherwise, integer order `n` only: the Neumann series (A&S 9.1.11)
///   with guard bits for the `e^{x}` cancellation.
fn arb_bessel_y(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let classic = arb_bessel_y_classic(order, x, prec, rm, cc);
    debye_fallback(bessel_debye::Kind::Y, order, x, prec, rm, cc, classic)
}

/// [`arb_bessel_y`] by the Hankel expansion and the Neumann series.
fn arb_bessel_y_classic(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let guard = 32;
    let wp = prec + guard;

    if x.is_zero() || x.is_negative() {
        return Err(SymplexError::Unevaluable {
            reason: "BesselY undefined at x ≤ 0".into(),
        });
    }

    refuse_bessel_argument(x, prec)?;
    let x_f64 = bigfloat_to_f64(x, rm, cc)?;
    let order_f64 = bigfloat_to_f64(order, rm, cc)?;
    let order_int = order_f64.round() as i64;
    // Exactly (see `arb_bessel_j`): a non-integer order near an integer is
    // refused below the Hankel range rather than taken for the integer.
    let is_int_order = order.is_int();

    // Negative integer order: Y_{-n}(x) = (-1)^n Y_n(x) (exactly, see
    // `arb_bessel_j`).
    if is_int_order && order.is_negative() {
        let y = arb_bessel_y(&order.neg(), x, prec, rm, cc)?;
        return Ok(if bessel_order::is_odd(order) {
            y.neg()
        } else {
            y
        });
    }

    if x_f64 >= hankel_threshold(wp, order_f64.abs())
        && let Some(y) = bessel_jy_hankel(order, x, false, wp, rm, cc)
    {
        tracing::trace!("arb_bessel_y: used Hankel P/Q expansion");
        return Ok(round_to(y, prec, rm));
    }

    // ── Small |x|, integer order n ≥ 0: Neumann series (A&S 9.1.11) ─────
    //
    //   Y_n(x) = −(1/π)(x/2)^{−n} Σ_{k=0}^{n−1} (n−k−1)!/k! (x²/4)^k
    //            + (2/π) ln(x/2) J_n(x)
    //            − (1/π)(x/2)^n Σ_{k≥0} [ψ(k+1) + ψ(n+k+1)] (−x²/4)^k / (k!(n+k)!)
    //
    // with ψ(m+1) = −γ + H_m.  Computed directly for every n (no forward
    // recurrence or Wronskian division, which is unstable near zeros of J).
    // The log term and the series cancel to O(e^{x}) relative size, so a
    // few extra guard bits are added.

    if !is_int_order {
        return Err(SymplexError::Unevaluable {
            reason: format!(
                "BesselY for non-integer order {order_f64} not yet implemented in small-|x| regime"
            ),
        });
    }
    // A large order: the finite part of the series alone where the rest is
    // negligible (`bessel_order::neumann_leading`).  Before 0.34 the series
    // took `n` steps in exact rationals: `bessely(5000, 1)` 17 s,
    // `bessely(10⁵, 1)` never finished.
    if order_f64 >= bessel_order::LARGE_ORDER {
        return bessel_order::neumann_leading(bessel_order::Second::Y, order, x, prec, rm, cc)
            .unwrap_or_else(|| Err(large_order_refused("bessely", order_f64, x_f64)));
    }
    let n = order_int as usize;
    // Beyond the cap of the cancellation, the finite part of the series alone
    // where the rest is negligible (`bessel_order::neumann_leading`): before
    // 0.35 `bessely(3909, 3909/2)` was refused.
    let guard = match series_guard_bits(x_f64, prec) {
        Ok(g) => g,
        Err(e) => {
            return bessel_order::neumann_leading(bessel_order::Second::Y, order, x, prec, rm, cc)
                .unwrap_or(Err(e));
        }
    };
    let wp = wp + guard;
    let mut xw = x.clone();
    let _ = xw.set_precision(wp, rm);

    let pi = cc.pi(wp, rm).clone();
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let inv_pi = one.div(&pi, wp, rm);
    let x_half = xw.div(&two, wp, rm);
    let x_half_sq = x_half.mul(&x_half, wp, rm);
    let ln_x_half = x_half.ln(wp, rm, cc);
    let euler_gamma = arb_euler_gamma(wp, rm, cc)?;
    let n_bf = BigFloat::from_i128(n as i128, wp);
    let j_n = arb_bessel_j(&n_bf, &xw, wp, rm, cc)?;

    // Finite sum: −(1/π)(x/2)^{−n} Σ_{k<n} (n−k−1)!/k! (x²/4)^k
    let mut finite = BigFloat::new(wp);
    if n > 0 {
        let mut f = NeumannCoefficients::new(n);
        let mut pow = one.clone();
        for k in 0..n {
            if k > 0 {
                pow = pow.mul(&x_half_sq, wp, rm);
            }
            let coeff = f.next(wp, rm);
            finite = finite.add(&coeff.mul(&pow, wp, rm), wp, rm);
        }
        let x_half_pow_neg_n = one.div(&x_half.powi(n, wp, rm), wp, rm);
        finite = inv_pi
            .mul(&x_half_pow_neg_n, wp, rm)
            .mul(&finite, wp, rm)
            .neg();
    }

    // Log term: (2/π) ln(x/2) J_n(x)
    let log_term = two
        .mul(&inv_pi, wp, rm)
        .mul(&ln_x_half, wp, rm)
        .mul(&j_n, wp, rm);

    // Series: −(1/π)(x/2)^n Σ_k [ψ(k+1) + ψ(n+k+1)] (−x²/4)^k / (k!(n+k)!)
    let mut h_k = BigFloat::new(wp);
    let mut h_nk = BigFloat::new(wp);
    for m in 1..=n {
        h_nk = h_nk.add(
            &one.div(&BigFloat::from_i128(m as i128, wp), wp, rm),
            wp,
            rm,
        );
    }
    let n_fact = factorial_exact(n);
    let mut inv_fact = one.div(&ratio_to_bigfloat(&n_fact, wp, rm), wp, rm);
    let neg_x_half_sq = x_half_sq.neg();
    let mut pow = one.clone();
    let mut series = BigFloat::new(wp);
    let two_gamma = euler_gamma.mul(&two, wp, rm);
    let max_terms = (x_f64.abs() * 2.0) as usize + wp + 40;
    for k in 0..=max_terms {
        if k > 0 {
            let k_bf = BigFloat::from_i128(k as i128, wp);
            let nk_bf = BigFloat::from_i128((n + k) as i128, wp);
            h_k = h_k.add(&one.div(&k_bf, wp, rm), wp, rm);
            h_nk = h_nk.add(&one.div(&nk_bf, wp, rm), wp, rm);
            inv_fact = inv_fact.div(&k_bf.mul(&nk_bf, wp, rm), wp, rm);
            pow = pow.mul(&neg_x_half_sq, wp, rm);
        }
        let psi_sum = h_k.add(&h_nk, wp, rm).sub(&two_gamma, wp, rm);
        let term = psi_sum.mul(&pow, wp, rm).mul(&inv_fact, wp, rm);
        series = series.add(&term, wp, rm);
        if k > 2
            && let (Some(t_exp), Some(s_exp)) = (term.exponent(), series.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            tracing::trace!(k, "arb_bessel_y: Neumann series converged");
            break;
        }
    }
    let series_term = inv_pi
        .mul(&x_half.powi(n, wp, rm), wp, rm)
        .mul(&series, wp, rm)
        .neg();

    let y = finite.add(&log_term, wp, rm).add(&series_term, wp, rm);
    Ok(round_to(y, prec, rm))
}

/// `n!` as an exact rational (an integer): a product of integers.  Not
/// `Ratio` arithmetic, whose every product is reduced by a gcd with the
/// denominator 1 — a binary gcd that takes a step per bit of the numerator,
/// `O(n²)` words for `n!`: before 0.34 `polygamma(1755, 1/10)` spent 5 s
/// in it in the fuzz build, `bessely(5000, 1)` 17 s.  The same value.
fn factorial_exact(n: usize) -> Ratio<BigInt> {
    Ratio::from_integer(crate::base::combinatorics::factorial(n as u64))
}

/// The coefficients `f_k = (n−k−1)!/k!`, `k = 0 … n−1`, of the finite sums of
/// `Y_n` and `K_n` (A&S 9.1.11, 9.6.11), as BigFloats: exactly the rounding of
/// the reduced fraction `ratio_to_bigfloat` made of the `Ratio` recurrence
/// `f_k = f_{k−1}/((n−k)·k)` before 0.34, without its gcds.  The reduced
/// fraction is an integer `(k+1)⋯(n−k−1)` while `k ≤ n−k−1` (`k!` divides
/// `(n−k−1)!`) and the unit fraction `1/((n−k)⋯k)` after: integer
/// recurrences with exact divisions and products.
struct NeumannCoefficients {
    n: usize,
    k: usize,
    /// `(n−k−1)!/k!` in the integer phase, the denominator in the other.
    value: BigInt,
}

impl NeumannCoefficients {
    fn new(n: usize) -> Self {
        let value = crate::base::combinatorics::factorial(n.saturating_sub(1) as u64);
        NeumannCoefficients { n, k: 0, value }
    }

    /// `f_k` at `wp` bits, then `k + 1`.
    fn next(&mut self, wp: usize, rm: RoundingMode) -> BigFloat {
        let (n, k) = (self.n, self.k);
        self.k += 1;
        if k > 0 {
            let (a, b) = (BigInt::from((n - k) as u64), BigInt::from(k as u64));
            if 2 * k < n {
                // (n−k)!/(k−1)! ÷ ((n−k)·k): exact.
                self.value = &self.value / (a * b);
            } else if 2 * k < n + 2 {
                // The first unit fraction: 1/k (n = 2k), 1/((k−1)·k) (n = 2k−1).
                self.value = (n - k..=k).map(|j| BigInt::from(j as u64)).product();
            } else {
                self.value = &self.value * a * b;
            }
        }
        if 2 * k < n {
            ratio_to_bigfloat(&Ratio::from_integer(self.value.clone()), wp, rm)
        } else {
            ratio_to_bigfloat(&Ratio::new_raw(BigInt::from(1), self.value.clone()), wp, rm)
        }
    }
}

/// `Y_n` or `K_n` of a large order where [`bessel_order::neumann_leading`]
/// does not apply (`x² > 2(n − 1)`): the full series would take `n` steps.
fn large_order_refused(what: &str, order: f64, x: f64) -> SymplexError {
    SymplexError::NotImplemented(format!(
        "{what} of integer order {order:e} at {x:e} (above sqrt(2n)): the Neumann series would \
         take n terms (no uniform asymptotic expansion)"
    ))
}

// ═══════════════════════════════════════════════════════════════════════════
// Catalan's constant
// ═══════════════════════════════════════════════════════════════════════════

/// Catalan's constant `G` at `prec` bits via Ramanujan's formula
///
/// ```text
/// G = (π/8)·ln(2 + √3) + (3/8)·Σ_{n≥0} 1 / ((2n+1)² · C(2n, n))
/// ```
///
/// The series gains ~2 bits per term (`1/C(2n,n) ~ 4^{-n}`), so about
/// `prec/2` terms are needed; every term is positive (no cancellation).
fn arb_catalan(prec: usize, rm: RoundingMode, cc: &mut Consts) -> Result<BigFloat, SymplexError> {
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let three = BigFloat::from_i32(3, wp);
    let eight = BigFloat::from_i32(8, wp);

    // (π/8)·ln(2 + √3)
    let sqrt3 = three.sqrt(wp, rm);
    let ln_term = two.add(&sqrt3, wp, rm).ln(wp, rm, cc);
    let pi = cc.pi(wp, rm).clone();
    let first = pi.div(&eight, wp, rm).mul(&ln_term, wp, rm);

    // Σ b_n / (2n+1)² with b_n = 1/C(2n,n), b_{n+1} = b_n·(n+1)/(2(2n+1)).
    let mut b = one.clone();
    let mut sum = BigFloat::new(wp);
    let max_terms = wp / 2 + 64;
    for n in 0..max_terms {
        let two_n_plus_1 = BigFloat::from_i128(2 * n as i128 + 1, wp);
        let denom = two_n_plus_1.mul(&two_n_plus_1, wp, rm);
        let term = b.div(&denom, wp, rm);
        sum = sum.add(&term, wp, rm);
        if let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            break;
        }
        let n_plus_1 = BigFloat::from_i128(n as i128 + 1, wp);
        let two_2n_plus_1 = two.mul(&two_n_plus_1, wp, rm);
        b = b.mul(&n_plus_1, wp, rm).div(&two_2n_plus_1, wp, rm);
    }
    let second = three.div(&eight, wp, rm).mul(&sum, wp, rm);
    let mut g = first.add(&second, wp, rm);
    g.set_precision(prec, rm)
        .map_err(|e| SymplexError::ComputationFailed {
            operation: "catalan",
            reason: format!("precision adjustment failed: {e:?}"),
        })?;
    Ok(g)
}

// ═══════════════════════════════════════════════════════════════════════════
// Trigonometric / exponential / logarithmic integrals
// ═══════════════════════════════════════════════════════════════════════════

/// Number of guard bits needed to absorb the cancellation in an
/// alternating power series whose largest term is `~e^{|x|}`.
fn cancellation_guard_bits(x_abs: f64) -> usize {
    (x_abs * std::f64::consts::LOG2_E).ceil() as usize + 32
}

/// [`cancellation_guard_bits`] for the power series of `J_ν` and `Y_n` at
/// `|x|`, refused beyond [`cancellation_cap`]: the series also takes about
/// `|x|` terms.  Before 0.30 nothing bounded them — `besselj(5/2, 10²⁵)`
/// asked for `1.4·10²⁵` bits and printed garbage (`3.8·10¹⁰⁵²⁷`).
fn series_guard_bits(x_abs: f64, prec: usize) -> Result<usize, SymplexError> {
    let guard = cancellation_guard_bits(x_abs);
    if !x_abs.is_finite() || guard > cancellation_cap(prec) {
        return Err(special_exhausted(prec));
    }
    Ok(guard)
}

/// Refuse a Bessel argument whose Hankel phase `x − νπ/2 − π/4` would
/// need more than [`cancellation_cap`] extra bits (`log₂|x|` of them, see
/// [`bessel_jy_hankel`]): `besselj(−5, erfi(1210))`, an argument of
/// `2^(2·10⁶)`, ran for minutes.
fn refuse_bessel_argument(x: &BigFloat, prec: usize) -> Result<(), SymplexError> {
    let cap = i64::try_from(cancellation_cap(prec)).unwrap_or(i64::MAX);
    if x.is_inf() || x.exponent().is_some_and(|e| i64::from(e) > cap) {
        return Err(special_exhausted(prec));
    }
    Ok(())
}

/// Auxiliary functions `f(x)`, `g(x)` of the asymptotic expansions
///
/// ```text
/// Si(x) = π/2 − f(x) cos x − g(x) sin x,   Ci(x) = f(x) sin x − g(x) cos x
/// f(x) ~ (1/x) Σ (−1)^k (2k)!/x^{2k},   g(x) ~ (1/x²) Σ (−1)^k (2k+1)!/x^{2k}
/// ```
///
/// for `x > 0`.  Uses optimal truncation (stop when terms grow); the
/// caller guarantees `x` is large enough that the smallest term is below
/// the working precision.
fn si_ci_asymptotic_fg(x: &BigFloat, wp: usize, rm: RoundingMode) -> (BigFloat, BigFloat) {
    let one = BigFloat::from_i32(1, wp);
    let inv_x = one.div(x, wp, rm);
    let inv_x2 = inv_x.mul(&inv_x, wp, rm);

    let mut f_sum = BigFloat::new(wp);
    let mut g_sum = BigFloat::new(wp);
    // t_f = (2k)!/x^{2k}, t_g = (2k+1)!/x^{2k}
    let mut t_f = one.clone();
    let mut t_g = one.clone();
    let mut prev_f: Option<BigFloat> = None;
    let max_terms = wp * 2 + 100;
    for k in 0..max_terms {
        if k > 0 {
            // (2k)! / (2k-2)! = (2k-1)(2k);  (2k+1)!/(2k-1)! = (2k)(2k+1)
            let a = BigFloat::from_i128((2 * k as i128 - 1) * (2 * k as i128), wp);
            let b = BigFloat::from_i128((2 * k as i128) * (2 * k as i128 + 1), wp);
            t_f = t_f.mul(&a, wp, rm).mul(&inv_x2, wp, rm);
            t_g = t_g.mul(&b, wp, rm).mul(&inv_x2, wp, rm);
        }
        // Optimal truncation: stop once terms start growing.
        if let Some(ref p) = prev_f
            && t_f.abs().cmp(p).is_some_and(|c| c > 0)
        {
            break;
        }
        if k % 2 == 0 {
            f_sum = f_sum.add(&t_f, wp, rm);
            g_sum = g_sum.add(&t_g, wp, rm);
        } else {
            f_sum = f_sum.sub(&t_f, wp, rm);
            g_sum = g_sum.sub(&t_g, wp, rm);
        }
        if let (Some(t_exp), Some(s_exp)) = (t_f.exponent(), f_sum.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            break;
        }
        prev_f = Some(t_f.abs());
    }
    (f_sum.mul(&inv_x, wp, rm), g_sum.mul(&inv_x2, wp, rm))
}

/// Sine and cosine integrals for real `x`.
///
/// * `want_si == true`: returns `(Si(x), 0)` — valid for all real `x`
///   (`Si` is odd).
/// * `want_si == false`: returns `(0, Ci(x))` — requires `x > 0`.
///
/// Power series for moderate `|x|` (with guard bits for the `e^{|x|}`
/// cancellation) and the Hankel-type asymptotic expansion when
/// `|x| > wp·ln 2` (where its optimal-truncation error `~e^{−x}` is below
/// the working precision).
fn arb_si_ci(
    x: &BigFloat,
    want_si: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, BigFloat), SymplexError> {
    if x.is_nan() || x.is_inf_pos() || x.is_inf_neg() {
        return Err(SymplexError::Unevaluable {
            reason: "Si/Ci of special float value".into(),
        });
    }
    let x_f64 = bigfloat_to_f64(x, rm, cc)?;
    let x_abs = x_f64.abs();
    let base_wp = prec + 32;

    if x.is_zero() {
        return if want_si {
            Ok((BigFloat::new(prec), BigFloat::new(prec)))
        } else {
            Err(SymplexError::Unevaluable {
                reason: "Ci(0) is zoo".into(),
            })
        };
    }
    if !want_si && x.is_negative() {
        return Err(SymplexError::Unevaluable {
            reason: "Ci requires a positive argument here".into(),
        });
    }

    // Far out `f`, `g` are below `2^−wp` next to π/2: `Si(x) = ±π/2`; `Ci(x)
    // ≈ sin(x)/x` needs `x` reduced modulo 2π, refused beyond
    // `cancellation_cap` bits (before 0.30 both reduced any `x`, and
    // `Si(erfi(765))`, `x ≈ 2^844000`, hung).
    let e = usize::try_from(x.exponent().map_or(0, i64::from).max(0)).unwrap_or(0);
    if e > base_wp + 2 {
        if !want_si {
            if e > cancellation_cap(prec) {
                return Err(special_exhausted(prec));
            }
        } else {
            let half_pi = cc
                .pi(base_wp, rm)
                .div(&BigFloat::from_i32(2, base_wp), base_wp, rm);
            let si = if x.is_negative() {
                half_pi.neg()
            } else {
                half_pi
            };
            return Ok((round_to(si, prec, rm), BigFloat::new(prec)));
        }
    }
    let switch = (base_wp as f64) * std::f64::consts::LN_2;
    if x_abs > switch {
        // ── Asymptotic expansion ──
        let wp = base_wp;
        let ax = x.abs();
        let (f, g) = si_ci_asymptotic_fg(&ax, wp, rm);
        let sin_x = ax.sin(wp, rm, cc);
        let cos_x = ax.cos(wp, rm, cc);
        let pi = cc.pi(wp, rm).clone();
        let two = BigFloat::from_i32(2, wp);
        let half_pi = pi.div(&two, wp, rm);
        let mut si =
            half_pi
                .sub(&f.mul(&cos_x, wp, rm), wp, rm)
                .sub(&g.mul(&sin_x, wp, rm), wp, rm);
        if x.is_negative() {
            si = si.neg();
        }
        let ci = f.mul(&sin_x, wp, rm).sub(&g.mul(&cos_x, wp, rm), wp, rm);
        return Ok((round_to(si, prec, rm), round_to(ci, prec, rm)));
    }

    // ── Power series ──
    let wp = base_wp + cancellation_guard_bits(x_abs);
    let mut xw = x.clone();
    let _ = xw.set_precision(wp, rm);
    let x2 = xw.mul(&xw, wp, rm);
    let max_terms = (x_abs * 1.5) as usize + wp + 40;

    let si = if want_si {
        // Si(x) = Σ (−1)^k t_k/(2k+1),  t_k = x^{2k+1}/(2k+1)!
        let mut t = xw.clone();
        let mut sum = BigFloat::new(wp);
        for k in 0..max_terms {
            if k > 0 {
                let d = BigFloat::from_i128((2 * k as i128) * (2 * k as i128 + 1), wp);
                t = t.mul(&x2, wp, rm).div(&d, wp, rm);
            }
            let term = t.div(&BigFloat::from_i128(2 * k as i128 + 1, wp), wp, rm);
            if k % 2 == 0 {
                sum = sum.add(&term, wp, rm);
            } else {
                sum = sum.sub(&term, wp, rm);
            }
            if let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
                && (s_exp as i64 - t_exp as i64) > wp as i64
            {
                break;
            }
        }
        round_to(sum, prec, rm)
    } else {
        BigFloat::new(prec)
    };

    let ci = if want_si {
        BigFloat::new(prec)
    } else {
        // Ci(x) = γ + ln x + Σ_{k≥1} (−1)^k u_k/(2k),  u_k = x^{2k}/(2k)!
        let gamma = arb_euler_gamma(wp, rm, cc)?;
        let ln_x = xw.ln(wp, rm, cc);
        let mut sum = BigFloat::new(wp);
        let mut u = BigFloat::from_i32(1, wp);
        for k in 1..max_terms {
            let d = BigFloat::from_i128((2 * k as i128 - 1) * (2 * k as i128), wp);
            u = u.mul(&x2, wp, rm).div(&d, wp, rm);
            let term = u.div(&BigFloat::from_i128(2 * k as i128, wp), wp, rm);
            if k % 2 == 0 {
                sum = sum.add(&term, wp, rm);
            } else {
                sum = sum.sub(&term, wp, rm);
            }
            if let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
                && (s_exp as i64 - t_exp as i64) > wp as i64
            {
                break;
            }
        }
        let ci = gamma.add(&ln_x, wp, rm).add(&sum, wp, rm);
        round_to(ci, prec, rm)
    };

    Ok((si, ci))
}

/// Exponential integral `Ei(x)` for real `x ≠ 0`.
///
/// * `|x| ≤ wp·ln 2`: `Ei(x) = γ + ln|x| + Σ_{k≥1} xᵏ/(k·k!)`, with guard
///   bits for the alternating cancellation when `x < 0`;
/// * otherwise the asymptotic expansion `Ei(x) ~ (eˣ/x) Σ k!/xᵏ` with
///   optimal truncation (relative error `~e^{−|x|}`).
fn arb_ei(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || x.is_inf_pos() || x.is_inf_neg() || x.is_zero() {
        return Err(SymplexError::Unevaluable {
            reason: "Ei of zero or special float value".into(),
        });
    }
    let x_f64 = bigfloat_to_f64(x, rm, cc)?;
    let x_abs = x_f64.abs();
    let base_wp = prec + 32;
    let switch = (base_wp as f64) * std::f64::consts::LN_2;

    if x_abs > switch {
        // ── Asymptotic: Ei(x) ~ (e^x / x) Σ_{k≥0} k! / x^k ──
        let wp = base_wp;
        let (inv_x, sum) = ei_asymptotic_series(x, wp, rm);
        let ex = x.exp(wp, rm, cc);
        let r = ex.mul(&inv_x, wp, rm).mul(&sum, wp, rm);
        return Ok(round_to(r, prec, rm));
    }

    // ── Power series ──
    // For x < 0 the terms reach `~e^{|x|}` and `Ei(x) ~ e^{−|x|}/|x|`: the
    // sum cancels about `2|x|·log₂e` bits, and the value near the zero
    // `x ≈ 0.3725` more.  The loss is measured (the largest term against
    // the value) and the series repeated with that many more bits, up to
    // `cancellation_cap`.  Before 0.30 the guard was `|x|·log₂e`, half
    // of it: `Ei(−196)` at 60 digits was wrong from its 24th digit.
    let cap = cancellation_cap(prec);
    let mut extra = if x.is_negative() {
        cancellation_guard_bits(2.0 * x_abs)
    } else {
        32
    };
    loop {
        let wp = prec + extra;
        let mut xw = x.clone();
        let _ = xw.set_precision(wp, rm);
        let gamma = arb_euler_gamma(wp, rm, cc)?;
        let ln_abs_x = xw.abs().ln(wp, rm, cc);
        let mut largest = gamma.abs().max(&ln_abs_x.abs());
        let mut v = BigFloat::from_i32(1, wp); // x^k/k!
        let mut sum = BigFloat::new(wp);
        let max_terms = (x_abs * 3.0) as usize + wp + 40;
        for k in 1..max_terms {
            let k_bf = BigFloat::from_i128(k as i128, wp);
            v = v.mul(&xw, wp, rm).div(&k_bf, wp, rm);
            let term = v.div(&k_bf, wp, rm);
            sum = sum.add(&term, wp, rm);
            largest = largest.max(&term.abs()).max(&sum.abs());
            if let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
                && (s_exp as i64 - t_exp as i64) > wp as i64
                && (k as f64) > x_abs
            {
                break;
            }
        }
        let r = gamma.add(&ln_abs_x, wp, rm).add(&sum, wp, rm);
        let lost = match (largest.exponent(), r.exponent()) {
            (Some(l), Some(v)) if !r.is_zero() => (i64::from(l) - i64::from(v)).max(0) as usize,
            _ => wp,
        };
        if lost + 32 <= extra {
            return Ok(round_to(r, prec, rm));
        }
        if extra >= cap {
            return Err(special_exhausted(prec));
        }
        extra = (lost + 64).min(cap).max(extra + 32);
    }
}

/// The asymptotic series of `Ei(x) ~ (e^x/x)·Σ_{k≥0} k!/x^k` at `wp` bits,
/// truncated at its smallest term: `(1/x, Σ)`.  [`arb_ei`] multiplies them
/// by `e^x`; `extended` by `e^x` at its own scale, below the exponent range.
fn ei_asymptotic_series(x: &BigFloat, wp: usize, rm: RoundingMode) -> (BigFloat, BigFloat) {
    let one = BigFloat::from_i32(1, wp);
    let inv_x = one.div(x, wp, rm);
    let mut term = one.clone();
    let mut sum = BigFloat::new(wp);
    let mut prev: Option<BigFloat> = None;
    let max_terms = wp * 2 + 100;
    for k in 0..max_terms {
        if k > 0 {
            term = term
                .mul(&BigFloat::from_i128(k as i128, wp), wp, rm)
                .mul(&inv_x, wp, rm);
        }
        if let Some(ref p) = prev
            && term.abs().cmp(p).is_some_and(|c| c > 0)
        {
            break;
        }
        sum = sum.add(&term, wp, rm);
        if let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            break;
        }
        prev = Some(term.abs());
    }
    (inv_x, sum)
}

/// Round a `BigFloat` down to `prec` bits (no-op on failure).
fn round_to(mut v: BigFloat, prec: usize, rm: RoundingMode) -> BigFloat {
    let _ = v.set_precision(prec, rm);
    v
}

/// `b^e` for real `b > 0` (or integer `e`), computed as `powi` for integer
/// exponents and `exp(e·ln b)` otherwise.
///
/// This deliberately avoids [`BigFloat::pow`], whose correct-rounding loop
/// never terminates when the exact result is representable in binary
/// (e.g. `4^{1/2} = 2`), which is exactly what happens for the integer
/// bases used in series like Borwein's `ζ` algorithm.
fn bf_pow(b: &BigFloat, e: &BigFloat, wp: usize, rm: RoundingMode, cc: &mut Consts) -> BigFloat {
    if e.is_zero() {
        return BigFloat::from_i32(1, wp);
    }
    if e.is_int()
        && let Ok(ef) = bigfloat_to_f64(e, rm, cc)
        && ef.abs() < 1.0e9
    {
        let n = ef.abs() as usize;
        let p = b.powi(n, wp, rm);
        return if ef < 0.0 {
            BigFloat::from_i32(1, wp).div(&p, wp, rm)
        } else {
            p
        };
    }
    let ln_b = b.ln(wp + 32, rm, cc);
    ln_b.mul(e, wp + 32, rm).exp(wp, rm, cc)
}

// ═══════════════════════════════════════════════════════════════════════════
// Riemann zeta function
// ═══════════════════════════════════════════════════════════════════════════

/// `ζ(s)` for real `s ≠ 1`.
///
/// * `s > 0`: Borwein's algorithm (P. Borwein, *An efficient algorithm for
///   the Riemann zeta function*, 1991, Algorithm 2) — an accelerated
///   alternating series with error `≤ 3/(3+√8)ⁿ`, so `n ≈ 0.39·wp` terms.
/// * `s < 0`: functional equation
///   `ζ(s) = 2ˢ π^{s−1} sin(πs/2) Γ(1−s) ζ(1−s)`; trivial zeros at the
///   negative even integers are returned exactly.
/// * `s = 0`: `−1/2`.
fn arb_zeta(
    s: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if s.is_nan() || s.is_inf_neg() {
        return Err(SymplexError::Unevaluable {
            reason: "zeta of special float value".into(),
        });
    }
    if s.is_inf_pos() {
        return Ok(BigFloat::from_i32(1, prec));
    }
    if s.is_zero() {
        return Ok(BigFloat::from_f64(-0.5, prec));
    }
    let s_f64 = bigfloat_to_f64(s, rm, cc)?;
    // The pole exactly (before 0.30 in `f64`, where `1 + 10⁻⁴⁵` is 1).
    if *s == BigFloat::from_i32(1, 64) {
        return Err(SymplexError::Unevaluable {
            reason: "zeta(1) is a pole".into(),
        });
    }
    let wp = prec + 32;

    if s.is_negative() {
        // Trivial zeros.
        let s_round = s_f64.round();
        if (s_f64 - s_round).abs() < 1e-14 && (s_round as i64) % 2 == 0 {
            let mut sw = s.clone();
            let _ = sw.set_precision(wp, rm);
            let diff = sw.sub(&BigFloat::from_f64(s_round, wp), wp, rm);
            if diff.is_zero() {
                return Ok(BigFloat::new(prec));
            }
        }
        // An `s` whose unit in the last place at the working precision is
        // 2 or more has no known parity: `sin(πs/2)` is undetermined (and
        // `ζ(s)` is a trivial zero or far beyond the exponent range).  The
        // argument reduction of that `sin` for `s ≈ −2^(1.4·10⁶)` ran for
        // minutes (`zeta(erfi(−1000))`, found by fuzz_evalf in 0.31).
        if s.exponent().is_some_and(|e| i64::from(e) > wp as i64) {
            return Err(special_exhausted(prec));
        }
        // ζ(s) = 2^s π^{s−1} sin(π s/2) Γ(1−s) ζ(1−s), `1 − s` exact: next
        // to 0 the factors `sin(πs/2) ≈ πs/2` and `ζ(1 − s) ≈ −1/s` are both
        // relative to `s` (before 0.30 `1 − s` was rounded, and `ζ(−10⁻⁶⁰)`
        // printed `−0.499999999999999999141761477346` at 30 digits).
        let mut sw = s.clone();
        let _ = sw.set_precision(wp, rm);
        let one = BigFloat::from_i32(1, wp);
        let two = BigFloat::from_i32(2, wp);
        let pi = cc.pi(wp, rm).clone();
        let one_minus_s = BigFloat::from_i32(1, 64).sub(s, exact_bits(s, wp), rm);
        let two_pow_s = bf_pow(&two, &sw, wp, rm, cc);
        let s_minus_1 = sw.sub(&one, wp, rm);
        let pi_pow = bf_pow(&pi, &s_minus_1, wp, rm, cc);
        let half_pi_s = pi.mul(&sw, wp, rm).div(&two, wp, rm);
        let sin_term = half_pi_s.sin(wp, rm, cc);
        let gamma_term = arb_gamma_real(&one_minus_s, wp, rm, cc)?;
        let zeta_term = arb_zeta_borwein(&one_minus_s, wp, rm, cc)?;
        let r = two_pow_s
            .mul(&pi_pow, wp, rm)
            .mul(&sin_term, wp, rm)
            .mul(&gamma_term, wp, rm)
            .mul(&zeta_term, wp, rm);
        return Ok(round_to(r, prec, rm));
    }

    let r = arb_zeta_borwein(s, wp, rm, cc)?;
    Ok(round_to(r, prec, rm))
}

/// Borwein's Algorithm 2 for `ζ(s)`, real `s > 0`, `s ≠ 1`:
/// `ζ(s) = η(s) / (1 − 2^{1−s})` with `η` from [`arb_eta_borwein`].
fn arb_zeta_borwein(
    s: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let eta = arb_eta_borwein(s, wp, rm, cc)?;
    // 1 − 2^{1−s} = −expm1((1 − s)·ln 2), with `1 − s` exact: next to the
    // pole the difference `1 − 2^{1−s}` cancels `log₂(1/|1 − s|)` bits, and
    // before 0.30 both were rounded (`ζ(1 + 10⁻⁴⁵)` was "a pole").
    let one_minus_s = BigFloat::from_i32(1, 64).sub(s, exact_bits(s, wp), rm);
    let denom_factor = one_minus_pow2(&one_minus_s, wp, rm, cc);
    if denom_factor.is_zero() {
        return Err(SymplexError::Unevaluable {
            reason: "zeta(1) is a pole".into(),
        });
    }
    Ok(eta.div(&denom_factor, wp, rm))
}

/// `1 − 2^t` to `wp` bits relative, also for a tiny `t` (where the
/// difference cancels): `−Σ_{k≥1} u^k/k!` with `u = t·ln 2` for `|u| < 1/4`.
fn one_minus_pow2(t: &BigFloat, wp: usize, rm: RoundingMode, cc: &mut Consts) -> BigFloat {
    if t.is_zero() {
        return BigFloat::new(wp);
    }
    let u = cc.ln_2(wp + 8, rm).mul(t, wp + 8, rm);
    if u.exponent().is_some_and(|e| e > -2) {
        return BigFloat::from_i32(1, wp).sub(&u.exp(wp + 8, rm, cc), wp, rm);
    }
    let mut term = u.clone();
    let mut sum = u.clone();
    for k in 2..(wp + 16) {
        term = term
            .mul(&u, wp + 8, rm)
            .div(&BigFloat::from_i128(k as i128, wp + 8), wp + 8, rm);
        sum = sum.add(&term, wp + 8, rm);
        if negligible(&term, &sum, wp + 8) {
            break;
        }
    }
    round_to(sum.neg(), wp, rm)
}

/// Borwein's accelerated alternating sum for the Dirichlet eta function
/// `η(s) = Σ_{k≥0} (−1)ᵏ/(k+1)ˢ`, real `s > 0` (P. Borwein, *An efficient
/// algorithm for the Riemann zeta function*, 1991, Algorithm 2; error
/// `≤ 3/(3+√8)ⁿ`, so `n ≈ 0.39·wp` terms):
///
/// ```text
/// d_k = n Σ_{i=0}^{k} (n+i−1)! 4ⁱ / ((n−i)! (2i)!)
/// η(s) = − 1/d_n · Σ_{k=0}^{n−1} (−1)ᵏ (d_k − d_n)/(k+1)ˢ
/// ```
fn arb_eta_borwein(
    s: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    // n such that (3+√8)^{-n} < 2^{-wp}:  n > wp·ln2/ln(3+√8) ≈ 0.393·wp
    let n = ((wp as f64) * std::f64::consts::LN_2 / (3.0 + 8f64.sqrt()).ln()).ceil() as usize + 4;

    // Exact integer coefficients d_k via rational arithmetic.
    let mut d: Vec<Ratio<BigInt>> = Vec::with_capacity(n + 1);
    let mut acc = Ratio::<BigInt>::zero();
    // term_i = n · (n+i−1)! · 4^i / ((n−i)! (2i)!)
    // term_0 = n · (n−1)!/n! = 1
    let mut term = Ratio::from_integer(BigInt::from(1));
    for i in 0..=n {
        if i > 0 {
            // term_i / term_{i−1} = (n+i−1)·4·(n−i+1) / ((2i−1)(2i))
            let numer = BigInt::from((n + i - 1) as u64)
                * BigInt::from(4u64)
                * BigInt::from((n - i + 1) as u64);
            let denom = BigInt::from((2 * i - 1) as u64) * BigInt::from((2 * i) as u64);
            term *= Ratio::new(numer, denom);
        }
        acc += &term;
        d.push(acc.clone());
    }
    let d_n = ratio_to_bigfloat(&d[n], wp, rm);

    // S = Σ_{k=0}^{n−1} (−1)^k (d_k − d_n) / (k+1)^s
    let mut sum = BigFloat::new(wp);
    let s_is_int = s.is_int();
    let s_int = if s_is_int {
        bigfloat_to_f64(s, rm, cc)?.round() as usize
    } else {
        0
    };
    // A non-integer power `m^s` costs a logarithm and an exponential, and
    // there are `0.39·wp` of them; `m^s = p^s·(m/p)^s` for the smallest
    // prime factor `p` of `m` leaves them to the primes (a seventh of
    // them at 4,000 bits, where `ζ` took seconds), each composite a product
    // of at most `log₂ m` roundings.
    let powers: Vec<BigFloat> = if s_is_int {
        Vec::new()
    } else {
        let mut spf = vec![0usize; n + 1];
        let mut table: Vec<BigFloat> = Vec::with_capacity(n + 1);
        table.push(BigFloat::new(wp));
        for m in 1..=n {
            if m >= 2 && spf[m] == 0 {
                for multiple in (m..=n).step_by(m) {
                    if spf[multiple] == 0 {
                        spf[multiple] = m;
                    }
                }
            }
            let v = if m == 1 {
                BigFloat::from_i32(1, wp)
            } else if spf[m] == m {
                bf_pow(&BigFloat::from_i128(m as i128, wp), s, wp + 8, rm, cc)
            } else {
                table[spf[m]].mul(&table[m / spf[m]], wp + 8, rm)
            };
            table.push(v);
        }
        table
    };
    for k in 0..n {
        let coeff = ratio_to_bigfloat(&(&d[k] - &d[n]), wp, rm);
        let kp1 = BigFloat::from_i128(k as i128 + 1, wp);
        let kp1_pow_s = if s_is_int {
            kp1.powi(s_int, wp, rm)
        } else {
            powers[k + 1].clone()
        };
        let term = coeff.div(&kp1_pow_s, wp, rm);
        if k % 2 == 0 {
            sum = sum.add(&term, wp, rm);
        } else {
            sum = sum.sub(&term, wp, rm);
        }
    }

    Ok(sum.div(&d_n, wp, rm).neg())
}

// ═══════════════════════════════════════════════════════════════════════════
// Polygamma
// ═══════════════════════════════════════════════════════════════════════════

/// `ψ⁽ⁿ⁾(x)` for integer `n ≥ 1` and real `x` (not a non-positive integer).
///
/// 1. Recurrence `ψ⁽ⁿ⁾(x) = ψ⁽ⁿ⁾(x+N) − (−1)ⁿ n! Σ_{k<N} 1/(x+k)^{n+1}`
///    shifts the argument to `x + N ≥ max(wp/3, n) + 10`.
/// 2. Asymptotic series (DLMF 5.15.8):
///    `ψ⁽ⁿ⁾(x) ~ (−1)^{n+1} [ (n−1)!/xⁿ + n!/(2x^{n+1}) + Σ_{k≥1} B₂ₖ (2k+n−1)!/((2k)! x^{2k+n}) ]`
///    with exact Bernoulli numbers, truncated when the terms fall below
///    the working precision (or start to diverge).
///
/// The shifted arguments `x + k` are exact, so a pole is only an integer
/// `x ≤ 0`; left of 0 the terms change sign and cancel near the zeros of
/// `ψ⁽ⁿ⁾` (for even `n`): the loss, the largest term over the value, is
/// measured and the evaluation repeated with that many more bits, up to
/// [`cancellation_cap`].  (Before 0.29 `x + k` was rounded at every step
/// and an `x + k` below `2^{−wp/2}` was taken for a pole:
/// `polygamma(1, −3 + √2·10⁻³⁰)` was refused at 16 digits.)
fn arb_polygamma(
    n: u32,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    _cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || x.is_inf_pos() || x.is_inf_neg() {
        return Err(SymplexError::Unevaluable {
            reason: "polygamma of special float value".into(),
        });
    }
    let cap = cancellation_cap(prec);
    let mut extra = 32;
    loop {
        let (value, largest) = polygamma_wp(n, x, prec + extra, rm)?;
        let lost = match (largest.exponent(), value.exponent()) {
            _ if value.is_zero() => prec + extra,
            (Some(l), Some(v)) => usize::try_from(i64::from(l) - i64::from(v)).unwrap_or(0),
            _ => 0,
        };
        if lost + 16 <= extra {
            return Ok(round_to(value, prec, rm));
        }
        if extra >= cap {
            return Err(special_exhausted(prec));
        }
        extra = (lost + 32).max(2 * extra).min(cap);
    }
}

/// `q·r` for a reduced fraction `q` and an integer `r`: the reduced fraction
/// `Ratio`'s product gives, with gcds against the denominator of `q` only
/// (of `r` modulo it) — not a binary gcd of `r` with 1, which takes a step
/// per bit of `r` (see [`factorial_exact`]).
fn times_integer(q: &Ratio<BigInt>, r: &BigInt) -> Ratio<BigInt> {
    use num_integer::Integer;
    use num_traits::One;
    let mut num = r.clone();
    let mut den = q.denom().clone();
    loop {
        let g = den.gcd(&(&num % &den));
        if g.is_one() || g.is_zero() {
            break;
        }
        num /= &g;
        den /= &g;
    }
    Ratio::new_raw(q.numer() * num, den)
}

/// `ψ⁽ⁿ⁾(x)` at working precision `wp` (see [`arb_polygamma`]) and the
/// magnitude of the largest term summed.
fn polygamma_wp(
    n: u32,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
) -> Result<(BigFloat, BigFloat), SymplexError> {
    let exact = exact_bits(x, wp);
    let n_us = n as usize;
    let one = BigFloat::from_i32(1, wp);

    // n! and (n−1)! as BigFloats (exact integers first: see `factorial_exact`).
    let nm1_fact = factorial_exact(n_us.saturating_sub(1));
    let n_fact = Ratio::from_integer(nm1_fact.numer() * BigInt::from(n_us as u64));
    let n_fact_bf = ratio_to_bigfloat(&n_fact, wp, rm);
    let nm1_fact_bf = ratio_to_bigfloat(&nm1_fact, wp, rm);
    // (−1)^{n+1}
    let outer_sign_neg = n_us.is_multiple_of(2);

    // ── Step 1: shift x upward ──
    let threshold_val = ((wp / 3).max(n_us) + 10) as i128;
    let threshold = BigFloat::from_i128(threshold_val, wp);
    // Far left of 0 the shift would take `|x|` steps: refused up front (a
    // refusal, not a failure — before 0.30 a million steps were taken and
    // then `ComputationFailed` raised, for `polygamma(100, erfi(−5))`).
    let max_steps = 10 * wp + 1_000_000;
    if bf_lt(x, &BigFloat::from_i128(-(max_steps as i128), wp)) {
        return Err(SymplexError::NotImplemented(
            "polygamma of an argument far left of 0 (the argument shift would take more \
             than a million steps)"
                .into(),
        ));
    }
    let mut xw = x.clone();
    let mut shift_sum = BigFloat::new(wp); // Σ 1/(x+k)^{n+1}
    let mut largest_inv = BigFloat::new(wp);
    let mut steps: usize = 0;
    while xw.sub(&threshold, wp, rm).is_negative() {
        if xw.is_zero() {
            return Err(SymplexError::Unevaluable {
                reason: "polygamma at non-positive integer pole".into(),
            });
        }
        let p = xw.powi(n_us + 1, wp, rm);
        let inv = one.div(&p, wp, rm);
        if inv.abs() > largest_inv {
            largest_inv = inv.abs();
        }
        shift_sum = shift_sum.add(&inv, wp, rm);
        xw = xw.add(&one, exact, rm);
        steps += 1;
        if steps > max_steps {
            return Err(SymplexError::NotImplemented(
                "polygamma: the argument shift did not terminate".into(),
            ));
        }
    }
    // ψ⁽ⁿ⁾(x) = ψ⁽ⁿ⁾(x+N) + (−1)^{n+1} n! Σ 1/(x+k)^{n+1}
    let shift_term = n_fact_bf.mul(&shift_sum, wp, rm);

    // ── Step 2: asymptotic series at xw ──
    // bracket = (n−1)!/x^n + n!/(2 x^{n+1}) + Σ B_{2k} (2k+n−1)!/((2k)! x^{2k+n})
    let x_pow_n = xw.powi(n_us, wp, rm);
    let x_pow_np1 = x_pow_n.mul(&xw, wp, rm);
    let two = BigFloat::from_i32(2, wp);
    let mut bracket = nm1_fact_bf.div(&x_pow_n, wp, rm);
    bracket = bracket.add(&n_fact_bf.div(&two.mul(&x_pow_np1, wp, rm), wp, rm), wp, rm);

    let x2 = xw.mul(&xw, wp, rm);
    let mut x_pow = x_pow_n.mul(&x2, wp, rm); // x^{n+2} for k = 1
    // (2k+n−1)!/(2k)! = (2k+1)⋯(2k+n−1), an integer: start k=1 → (n+1)!/2!
    // (exact integer steps, the same values as the `Ratio` steps before
    // 0.34 without their gcds).
    let mut ratio_fact = n_fact.numer() * BigInt::from(n_us as u64 + 1) / BigInt::from(2);
    let mut prev_term_exp: Option<i32> = None;
    let max_terms = wp / 2 + 20;
    for k in 1..=max_terms {
        if k > 1 {
            // multiply by (2k+n−2)(2k+n−1) / ((2k−1)(2k))
            let a =
                BigInt::from((2 * k + n_us - 2) as u64) * BigInt::from((2 * k + n_us - 1) as u64);
            let b = BigInt::from((2 * k - 1) as u64) * BigInt::from((2 * k) as u64);
            ratio_fact = ratio_fact * a / b;
            x_pow = x_pow.mul(&x2, wp, rm);
        }
        let b2k = bernoulli::even(k);
        let coeff = ratio_to_bigfloat(&times_integer(&b2k, &ratio_fact), wp, rm);
        let term = coeff.div(&x_pow, wp, rm);
        if let Some(t_exp) = term.exponent() {
            if let Some(prev) = prev_term_exp
                && t_exp > prev + 10
            {
                break; // diverging
            }
            prev_term_exp = Some(t_exp);
            if let Some(b_exp) = bracket.exponent()
                && (b_exp as i64 - t_exp as i64) > wp as i64
            {
                bracket = bracket.add(&term, wp, rm);
                break;
            }
        }
        bracket = bracket.add(&term, wp, rm);
    }

    let total = bracket.add(&shift_term, wp, rm);
    let result = if outer_sign_neg { total.neg() } else { total };
    let largest_shift = n_fact_bf.mul(&largest_inv, wp, rm);
    let largest = if largest_shift > bracket.abs() {
        largest_shift
    } else {
        bracket.abs()
    };
    Ok((result, largest))
}

// ═══════════════════════════════════════════════════════════════════════════
// Modified Bessel functions
// ═══════════════════════════════════════════════════════════════════════════

/// Ascending series for `I_ν(x)` at working precision `wp`:
/// `I_ν(x) = (x/2)^ν Σ_{k≥0} (x²/4)^k / (k! Γ(ν+k+1))`.
///
/// All terms are positive for `x > 0`, so no cancellation occurs; the
/// number of terms is `O(|x| + wp)`.
fn bessel_i_series(
    order: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let two = BigFloat::from_i32(2, wp);
    let x_half = x.div(&two, wp, rm);
    let x_half_sq = x_half.mul(&x_half, wp, rm);
    let order_f64 = bigfloat_to_f64(order, rm, cc)?;
    let order_int = order_f64.round() as i64;
    // Exactly (see `arb_bessel_j`).
    let is_int_order = order.is_int();

    if x.is_zero() {
        return if is_int_order && order_int == 0 {
            Ok(BigFloat::from_i32(1, wp))
        } else if order_f64 > 0.0 {
            Ok(BigFloat::new(wp))
        } else {
            Err(SymplexError::Unevaluable {
                reason: "BesselI at x=0 with negative order".into(),
            })
        };
    }

    if !is_int_order && x.is_negative() {
        return Err(SymplexError::Unevaluable {
            reason: "BesselI of negative argument with non-integer order is complex".into(),
        });
    }
    let one = BigFloat::from_i32(1, wp);
    let x_f64 = bigfloat_to_f64(x, rm, cc)?.abs();
    // A large order (I₋ₙ = Iₙ): the factor (x/2)^ν/Γ(ν+1) at once, its
    // exponent to an absolute 2^(−wp) (`bessel_order`), the series from 1 —
    // refused when it would be long.  Before 0.34 an order beyond 2⁶³
    // saturated an `i64`, and `besseli(10¹², 10¹¹)` summed for ever.
    let large = order_f64.abs() >= bessel_order::LARGE_ORDER;
    let (prefix, eff_order, mut term) = if large {
        let eff_order = if is_int_order {
            order.abs()
        } else {
            order.clone()
        };
        let eff_f64 = bigfloat_to_f64_rounded(&eff_order, rm)?;
        let bounds = bessel_order::series_bounds(eff_f64, x_f64, false);
        // Below the range: 0, which the accuracy layer holds as the
        // underflow of a nonzero `I_ν` (`underflowed`), as before 0.34.
        let Some(p) = bessel_order::power_over_gamma(
            &eff_order,
            &x_half.abs(),
            bounds,
            "besseli",
            wp,
            rm,
            cc,
        )?
        else {
            return Ok(BigFloat::new(wp));
        };
        bessel_order::refuse_long_i_series(eff_f64, x_f64)?;
        // I_n(−x) = (−1)ⁿ I_n(x).
        let p = if x.is_negative() && bessel_order::is_odd(order) {
            p.neg()
        } else {
            p
        };
        (p, eff_order, one.clone())
    } else {
        // (x/2)^ν
        let prefix = if is_int_order && order_int >= 0 {
            x_half.powi(order_int as usize, wp, rm)
        } else if is_int_order {
            // Negative integer order: I_{-n} = I_n.
            x_half.powi((-order_int) as usize, wp, rm)
        } else {
            let ln_xh = x_half.ln(wp, rm, cc);
            order.mul(&ln_xh, wp, rm).exp(wp, rm, cc)
        };
        let eff_order = if is_int_order && order_int < 0 {
            BigFloat::from_i128((-order_int) as i128, wp)
        } else {
            order.clone()
        };
        // term_0 = 1/Γ(ν+1)
        let gamma_nu1 = arb_gamma_real(&eff_order.add(&one, wp, rm), wp, rm, cc)?;
        let term = one.div(&gamma_nu1, wp, rm);
        (prefix, eff_order, term)
    };

    // term_{k+1} = term_k · (x²/4) / ((k+1)(ν+k+1))
    let mut sum = term.clone();
    let max_terms = (x_f64 * 2.0) as usize + wp + 40;
    for k in 1..=max_terms {
        let k_bf = BigFloat::from_i128(k as i128, wp);
        let nu_plus_k = eff_order.add(&k_bf, wp, rm);
        let denom = k_bf.mul(&nu_plus_k, wp, rm);
        term = term.mul(&x_half_sq, wp, rm).div(&denom, wp, rm);
        sum = sum.add(&term, wp, rm);
        if let (Some(t_exp), Some(s_exp)) = (term.exponent(), sum.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            break;
        }
    }
    let r = prefix.mul(&sum, wp, rm);
    if large && (r.is_zero() || r.is_inf()) {
        return Err(SymplexError::Unevaluable {
            reason: "besseli of large order: the value leaves the arbitrary-precision exponent \
                     range"
                .into(),
        });
    }
    Ok(r)
}

/// Asymptotic expansion of `I_ν(x)` for large `x > 0` (DLMF 10.40.1):
///
/// ```text
/// I_ν(x) ~ e^x/√(2πx) · Σ_k (−1)^k a_k(ν)/x^k,
/// a_k(ν) = (4ν² − 1²)(4ν² − 3²)⋯(4ν² − (2k−1)²) / (k!·8^k),
/// ```
///
/// the coefficients of [`hankel_pq`].  The part it leaves out is `~e^{−2x}`
/// relative to the value, below `2^{−wp}` from [`hankel_threshold`] on;
/// the sum stops at a term below `2^{−wp}` relative (or ends, for a
/// half-integer order).  `None` when the terms start growing first (an
/// order large next to `x`).
fn bessel_i_asymptotic(
    order: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Option<BigFloat> {
    let one = BigFloat::from_i32(1, wp);
    let eight = BigFloat::from_i32(8, wp);
    let four_nu_sq = BigFloat::from_i32(4, wp).mul(&order.mul(order, wp, rm), wp, rm);
    let inv_x = one.div(x, wp, rm);
    let mut a = one.clone(); // a_k/x^k
    let mut sum = one.clone();
    let mut prev = one.clone();
    let mut converged = false;
    for k in 1..(4 * wp + 100) {
        let two_km1 = BigFloat::from_i128(2 * k as i128 - 1, wp);
        let numer = four_nu_sq.sub(&two_km1.mul(&two_km1, wp, rm), wp, rm);
        let denom = eight.mul(&BigFloat::from_i128(k as i128, wp), wp, rm);
        a = a
            .mul(&numer, wp, rm)
            .div(&denom, wp, rm)
            .mul(&inv_x, wp, rm);
        if a.is_zero() {
            converged = true;
            break;
        }
        // A growing term, or one beyond the leading 1: an alternating sum
        // that would cancel bits the working precision does not carry.
        let size = a.abs();
        if size.cmp(&prev).is_some_and(|c| c > 0) || size.exponent().is_some_and(|e| e > 0) {
            break;
        }
        sum = if k % 2 == 1 {
            sum.sub(&a, wp, rm)
        } else {
            sum.add(&a, wp, rm)
        };
        if let (Some(t), Some(s)) = (a.exponent(), sum.exponent())
            && i64::from(s) - i64::from(t) > wp as i64
        {
            converged = true;
            break;
        }
        prev = size;
    }
    if !converged {
        return None;
    }
    let two_pi_x = cc
        .pi(wp, rm)
        .mul(&BigFloat::from_i32(2, wp), wp, rm)
        .mul(x, wp, rm);
    let amplitude = two_pi_x.sqrt(wp, rm).reciprocal(wp, rm);
    Some(x.exp(wp, rm, cc).mul(&amplitude, wp, rm).mul(&sum, wp, rm))
}

/// Modified Bessel function of the first kind `I_ν(x)` (real `ν`, `x`).
///
/// * `|x|` from [`hankel_threshold`] on: the asymptotic expansion
///   ([`bessel_i_asymptotic`]), with `I_n(−x) = (−1)ⁿ I_n(x)`;
/// * otherwise, or where the expansion does not converge, the ascending
///   series ([`bessel_i_series`], about `|x| + wp` terms), refused beyond
///   [`cancellation_cap`] terms.
///
/// Before 0.30 the series served every `x`: `besseli(5/2, 5.2·10⁷⁰)`
/// printed `2.18·10⁴⁴⁸⁵⁷` (truly beyond the exponent range),
/// `besseli(2, 10¹⁶)` and `besseli(0, 32/15·10⁸)` hung.
fn arb_bessel_i(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let classic = arb_bessel_i_classic(order, x, prec, rm, cc);
    debye_fallback(bessel_debye::Kind::I, order, x, prec, rm, cc, classic)
}

/// [`arb_bessel_i`] by the asymptotic expansion and the ascending series.
fn arb_bessel_i_classic(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let wp = prec + 32;
    if x.is_inf() {
        return Err(special_exhausted(prec));
    }
    let x_abs = bigfloat_to_f64(x, rm, cc)?.abs();
    let order_f64 = bigfloat_to_f64(order, rm, cc)?;
    if x_abs >= hankel_threshold(wp, order_f64.abs()) {
        if x.is_negative() {
            if !order.is_int() {
                return Err(SymplexError::Unevaluable {
                    reason: "BesselI of negative argument with non-integer order is complex".into(),
                });
            }
            let v = arb_bessel_i(order, &x.abs(), prec, rm, cc)?;
            return Ok(if bessel_order::is_odd(order) {
                v.neg()
            } else {
                v
            });
        }
        if let Some(v) = bessel_i_asymptotic(order, x, wp, rm, cc) {
            return Ok(round_to(v, prec, rm));
        }
        if !x_abs.is_finite() || x_abs > cancellation_cap(prec) as f64 {
            return Err(special_exhausted(prec));
        }
    }
    let r = bessel_i_series(order, x, wp, rm, cc)?;
    Ok(round_to(r, prec, rm))
}

/// Asymptotic expansion for `K_ν(x)`, large `x > 0` (DLMF 10.40.2):
/// `K_ν(x) ~ √(π/(2x)) e^{−x} Σ_k a_k(ν)/x^k`,
/// `a_k(ν) = ∏_{j=1}^{k} (4ν² − (2j−1)²) / (k! 8^k)`.
///
/// While `(2k−1)² < 4ν²` the terms are positive and may grow (an order
/// large next to `x`); past that they alternate, and the first one that
/// grows marks the divergence of the expansion.  `None` when the terms do
/// not fall below `2^{−wp}` relative before that (the caller uses the
/// series); a half-integer order ends the expansion exactly.  Before 0.30
/// the first growing term stopped the sum, whatever the order, and the
/// partial sum was returned: `besselk(20, 60)` was `6.14·10⁻²⁷` (truly
/// `3.75·10⁻²⁶`), `besselk(50, 100)` `6.29·10⁻⁴⁴` (truly
/// `9.27·10⁻⁴⁰`), both certified.
fn bessel_k_asymptotic(
    order: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Option<BigFloat> {
    let one = BigFloat::from_i32(1, wp);
    let four = BigFloat::from_i32(4, wp);
    let eight = BigFloat::from_i32(8, wp);
    let four_nu_sq = four.mul(&order.mul(order, wp, rm), wp, rm);
    let inv_x = one.div(x, wp, rm);
    let mut a_k = one.clone();
    let mut sum = one.clone();
    let mut prev: Option<BigFloat> = None;
    let mut converged = false;
    let max_terms = wp * 2 + 100;
    for k in 1..max_terms {
        let two_km1 = BigFloat::from_i128(2 * k as i128 - 1, wp);
        let two_km1_sq = two_km1.mul(&two_km1, wp, rm);
        let numer = four_nu_sq.sub(&two_km1_sq, wp, rm);
        let denom = eight.mul(&BigFloat::from_i128(k as i128, wp), wp, rm);
        a_k = a_k
            .mul(&numer, wp, rm)
            .div(&denom, wp, rm)
            .mul(&inv_x, wp, rm);
        if a_k.is_zero() {
            converged = true;
            break;
        }
        let alternating = two_km1_sq.cmp(&four_nu_sq).is_some_and(|c| c > 0);
        if alternating
            && let Some(ref p) = prev
            && a_k.abs().cmp(p).is_some_and(|c| c > 0)
        {
            break;
        }
        sum = sum.add(&a_k, wp, rm);
        if let (Some(t_exp), Some(s_exp)) = (a_k.exponent(), sum.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            converged = true;
            break;
        }
        prev = Some(a_k.abs());
    }
    if !converged {
        return None;
    }
    let pi = cc.pi(wp, rm).clone();
    let two = BigFloat::from_i32(2, wp);
    let amp = pi.div(&two.mul(x, wp, rm), wp, rm).sqrt(wp, rm);
    let e_neg_x = x.neg().exp(wp, rm, cc);
    Some(amp.mul(&e_neg_x, wp, rm).mul(&sum, wp, rm))
}

/// Modified Bessel function of the second kind `K_ν(x)`, `x > 0`.
///
/// * Large `x` (`2x > wp·ln 2`): asymptotic expansion.
/// * Integer order `n` (A&S 9.6.11):
///   `K_n(x) = ½(x/2)^{−n} Σ_{k<n} (n−k−1)!/k! (−x²/4)^k + (−1)^{n+1} ln(x/2) I_n(x)
///           + (−1)^n ½ (x/2)^n Σ_{k≥0} [ψ(k+1) + ψ(n+k+1)] (x²/4)^k/(k!(n+k)!)`
///   with `ψ(m+1) = −γ + H_m`.
/// * Non-integer order: `K_ν = (π/2)(I_{−ν} − I_ν)/sin(νπ)`.
///
/// Both series formulas suffer `e^{x}`-scale cancellation (the result is
/// `~e^{−x}`), which is absorbed by extra guard bits.
fn arb_bessel_k(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let classic = arb_bessel_k_classic(order, x, prec, rm, cc);
    debye_fallback(bessel_debye::Kind::K, order, x, prec, rm, cc, classic)
}

/// [`arb_bessel_k`] by the asymptotic expansion and the series.
fn arb_bessel_k_classic(
    order: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_zero() || x.is_negative() || x.is_nan() {
        return Err(SymplexError::Unevaluable {
            reason: "BesselK undefined at x ≤ 0".into(),
        });
    }
    let base_wp = prec + 32;
    let x_f64 = bigfloat_to_f64(x, rm, cc)?;
    let order_f64 = bigfloat_to_f64(order, rm, cc)?;
    let order_int = order_f64.round() as i64;
    // Exactly (see `arb_bessel_j`); a non-integer order near an integer is
    // paid for with precision below.
    let is_int_order = order.is_int();
    // |n| exactly (before 0.34 through a saturating `i64`).
    let order_abs = if is_int_order && order_f64.abs() < bessel_order::LARGE_ORDER {
        BigFloat::from_i128(order_int.unsigned_abs() as i128, base_wp)
    } else {
        order.abs()
    };

    // Large x: asymptotic (relative truncation error ~ e^{-2x}).
    if 2.0 * x_f64 > (base_wp as f64) * std::f64::consts::LN_2
        && let Some(r) = bessel_k_asymptotic(&order_abs, x, base_wp, rm, cc)
    {
        return Ok(round_to(r, prec, rm));
    }

    // Series: guard against e^{x} cancellation (two exponentially large
    // terms of opposite sign nearly cancel).
    let wp = base_wp + 2 * series_guard_bits(x_f64, prec)?;
    let mut xw = x.clone();
    let _ = xw.set_precision(wp, rm);

    if !is_int_order {
        // K_ν = (π/2)(I_{−ν} − I_ν)/sin(νπ), with sin(νπ) = (−1)ⁿ sin(dπ),
        // ν = n + d exactly.  Near an integer order the difference cancels
        // log₂(1/|d|) bits (and more against e^{x}): the loss is measured
        // and the series repeated with that many more bits, up to
        // `cancellation_cap`.  (Before 0.29 an order within 10⁻¹² of an
        // integer was taken for it — `besselk(1 + 10⁻¹⁴, 1)` was wrong from
        // its 15th digit — and one a little further lost its bits unseen.)
        let exact = exact_bits(order, wp);
        let n = order.add(&BigFloat::from_f64(0.5, 64), exact, rm).floor();
        let d = order.sub(&n, exact, rm);
        let odd = !n
            .div(&BigFloat::from_i32(2, 64), exact, rm)
            .fract()
            .is_zero();
        let neg_order = order.neg();
        let cap = cancellation_cap(prec);
        let mut extra = wp - prec;
        loop {
            let wq = prec + extra;
            let mut xq = x.clone();
            let _ = xq.set_precision(wq, rm);
            let i_neg = bessel_i_series(&neg_order, &xq, wq, rm, cc)?;
            let i_pos = bessel_i_series(order, &xq, wq, rm, cc)?;
            let diff = i_neg.sub(&i_pos, wq, rm);
            let big = if i_neg.abs() > i_pos.abs() {
                i_neg.abs()
            } else {
                i_pos.abs()
            };
            let lost = match (big.exponent(), diff.exponent()) {
                _ if diff.is_zero() => wq,
                (Some(b), Some(e)) => usize::try_from(i64::from(b) - i64::from(e)).unwrap_or(0),
                _ => 0,
            };
            if lost + 16 <= extra {
                let pi = cc.pi(wq, rm).clone();
                let two = BigFloat::from_i32(2, wq);
                let mut sin_nu_pi = d.mul(&pi, wq, rm).sin(wq, rm, cc);
                if odd {
                    sin_nu_pi = sin_nu_pi.neg();
                }
                let r = pi
                    .div(&two, wq, rm)
                    .mul(&diff, wq, rm)
                    .div(&sin_nu_pi, wq, rm);
                return Ok(round_to(r, prec, rm));
            }
            if extra >= cap {
                return Err(special_exhausted(prec));
            }
            extra = (lost + 48).max(2 * extra).min(cap);
        }
    }

    // A large order (K₋ₙ = Kₙ): the finite part of the series alone where
    // the rest is negligible (`bessel_order::neumann_leading`).  Before 0.34
    // the series took `n` steps in exact rationals (`besselk(5000, 1)` never
    // finished) and an order beyond 2⁶³ saturated.
    if order_f64.abs() >= bessel_order::LARGE_ORDER {
        return bessel_order::neumann_leading(bessel_order::Second::K, &order_abs, x, prec, rm, cc)
            .unwrap_or_else(|| Err(large_order_refused("besselk", order_f64, x_f64)));
    }
    let n = order_int.unsigned_abs() as usize;
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let half = one.div(&two, wp, rm);
    let x_half = xw.div(&two, wp, rm);
    let x_half_sq = x_half.mul(&x_half, wp, rm);
    let ln_x_half = x_half.ln(wp, rm, cc);
    let gamma = arb_euler_gamma(wp, rm, cc)?;
    let n_bf = BigFloat::from_i128(n as i128, wp);
    let i_n = bessel_i_series(&n_bf, &xw, wp, rm, cc)?;

    // Finite sum: ½ (x/2)^{-n} Σ_{k=0}^{n-1} (n−k−1)!/k! (−x²/4)^k
    let mut finite = BigFloat::new(wp);
    if n > 0 {
        // f_k = (n−k−1)!/k! ; f_0 = (n−1)!
        let mut f = NeumannCoefficients::new(n);
        let mut pow = one.clone(); // (−x²/4)^k
        let neg_x_half_sq = x_half_sq.neg();
        for k in 0..n {
            if k > 0 {
                pow = pow.mul(&neg_x_half_sq, wp, rm);
            }
            let coeff = f.next(wp, rm);
            finite = finite.add(&coeff.mul(&pow, wp, rm), wp, rm);
        }
        let x_half_pow_neg_n = one.div(&x_half.powi(n, wp, rm), wp, rm);
        finite = half.mul(&x_half_pow_neg_n, wp, rm).mul(&finite, wp, rm);
    }

    // Log term: (−1)^{n+1} ln(x/2) I_n(x)
    let log_term = ln_x_half.mul(&i_n, wp, rm);
    let log_term = if n.is_multiple_of(2) {
        log_term.neg()
    } else {
        log_term
    };

    // Infinite sum: (−1)^n ½ (x/2)^n Σ_k [ψ(k+1) + ψ(n+k+1)] (x²/4)^k/(k!(n+k)!)
    // ψ(m+1) = −γ + H_m.
    let mut h_k = BigFloat::new(wp); // H_0 = 0
    let mut h_nk = BigFloat::new(wp); // H_n
    for m in 1..=n {
        h_nk = h_nk.add(
            &one.div(&BigFloat::from_i128(m as i128, wp), wp, rm),
            wp,
            rm,
        );
    }
    // 1/(k!(n+k)!) start: 1/n!
    let n_fact = factorial_exact(n);
    let mut inv_fact = one.div(&ratio_to_bigfloat(&n_fact, wp, rm), wp, rm);
    let mut pow = one.clone();
    let mut series = BigFloat::new(wp);
    let two_gamma = gamma.mul(&two, wp, rm);
    let max_terms = (x_f64 * 2.0) as usize + wp + 40;
    for k in 0..=max_terms {
        if k > 0 {
            let k_bf = BigFloat::from_i128(k as i128, wp);
            let nk_bf = BigFloat::from_i128((n + k) as i128, wp);
            h_k = h_k.add(&one.div(&k_bf, wp, rm), wp, rm);
            h_nk = h_nk.add(&one.div(&nk_bf, wp, rm), wp, rm);
            inv_fact = inv_fact.div(&k_bf.mul(&nk_bf, wp, rm), wp, rm);
            pow = pow.mul(&x_half_sq, wp, rm);
        }
        let psi_sum = h_k.add(&h_nk, wp, rm).sub(&two_gamma, wp, rm);
        let term = psi_sum.mul(&pow, wp, rm).mul(&inv_fact, wp, rm);
        series = series.add(&term, wp, rm);
        if k > 2
            && let (Some(t_exp), Some(s_exp)) = (term.exponent(), series.exponent())
            && (s_exp as i64 - t_exp as i64) > wp as i64
        {
            break;
        }
    }
    let series_term = half
        .mul(&x_half.powi(n, wp, rm), wp, rm)
        .mul(&series, wp, rm);
    let series_term = if n.is_multiple_of(2) {
        series_term
    } else {
        series_term.neg()
    };

    let r = finite.add(&log_term, wp, rm).add(&series_term, wp, rm);
    Ok(round_to(r, prec, rm))
}

// ═══════════════════════════════════════════════════════════════════════════
// Orthogonal polynomials
// ═══════════════════════════════════════════════════════════════════════════

/// Families of classical orthogonal polynomials evaluated numerically.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum OrthoPoly {
    Legendre,
    ChebyshevT,
    ChebyshevU,
    Hermite,
    Laguerre,
}

/// Evaluate `P_n(x)` (or `T_n`, `U_n`, `H_n`, `L_n`) for any non-negative
/// integer `n` via the three-term recurrence:
///
/// * Legendre: `(k+1) P_{k+1} = (2k+1) x P_k − k P_{k−1}`
/// * Chebyshev T/U: `T_{k+1} = 2x T_k − T_{k−1}` (`T_1 = x`, `U_1 = 2x`)
/// * Hermite (physicists'): `H_{k+1} = 2x H_k − 2k H_{k−1}`
/// * Laguerre: `(k+1) L_{k+1} = (2k+1−x) L_k − k L_{k−1}`
fn arb_orthopoly(kind: OrthoPoly, n: u64, x: &BigFloat, prec: usize, rm: RoundingMode) -> BigFloat {
    let wp = prec + 32 + (n as f64).log2().ceil().max(0.0) as usize;
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let mut xw = x.clone();
    let _ = xw.set_precision(wp, rm);
    if n == 0 {
        return BigFloat::from_i32(1, prec);
    }
    let mut p_prev = one.clone();
    let mut p_curr = match kind {
        OrthoPoly::Legendre | OrthoPoly::ChebyshevT => xw.clone(),
        OrthoPoly::ChebyshevU | OrthoPoly::Hermite => two.mul(&xw, wp, rm),
        OrthoPoly::Laguerre => one.sub(&xw, wp, rm),
    };
    for k in 1..n {
        let k_bf = BigFloat::from_i128(k as i128, wp);
        let kp1 = BigFloat::from_i128(k as i128 + 1, wp);
        let next = match kind {
            OrthoPoly::Legendre => {
                let two_k_plus_1 = BigFloat::from_i128(2 * k as i128 + 1, wp);
                let a = two_k_plus_1.mul(&xw, wp, rm).mul(&p_curr, wp, rm);
                let b = k_bf.mul(&p_prev, wp, rm);
                a.sub(&b, wp, rm).div(&kp1, wp, rm)
            }
            OrthoPoly::ChebyshevT | OrthoPoly::ChebyshevU => two
                .mul(&xw, wp, rm)
                .mul(&p_curr, wp, rm)
                .sub(&p_prev, wp, rm),
            OrthoPoly::Hermite => {
                let a = two.mul(&xw, wp, rm).mul(&p_curr, wp, rm);
                let b = two.mul(&k_bf, wp, rm).mul(&p_prev, wp, rm);
                a.sub(&b, wp, rm)
            }
            OrthoPoly::Laguerre => {
                let two_k_plus_1 = BigFloat::from_i128(2 * k as i128 + 1, wp);
                let a = two_k_plus_1.sub(&xw, wp, rm).mul(&p_curr, wp, rm);
                let b = k_bf.mul(&p_prev, wp, rm);
                a.sub(&b, wp, rm).div(&kp1, wp, rm)
            }
        };
        p_prev = p_curr;
        p_curr = next;
    }
    round_to(p_curr, prec, rm)
}

// ═══════════════════════════════════════════════════════════════════════════
// More special functions (0.9)
// ═══════════════════════════════════════════════════════════════════════════
//
// All routines take real arguments and return real results at `prec` bits;
// complex arguments and points outside the real domain of a function are
// refused with `Unevaluable`.  Working precision is `prec + 32` plus
// problem-dependent guard bits wherever an alternating series or a
// difference of nearly equal quantities loses digits.

fn unevaluable(reason: impl Into<String>) -> SymplexError {
    SymplexError::Unevaluable {
        reason: reason.into(),
    }
}

/// A series exhausted its term budget without meeting the negligibility
/// test; the partial sum is *not* returned.
fn series_did_not_converge(operation: &'static str, max_terms: usize) -> SymplexError {
    SymplexError::ComputationFailed {
        operation,
        reason: format!("series did not converge in {max_terms} terms"),
    }
}

/// The cached values of `args`, all required to be real.
fn real_args(
    name: &str,
    args: &[ExprId],
    cache: &FxHashMap<ExprId, Complex>,
) -> Result<Vec<BigFloat>, SymplexError> {
    let mut out = Vec::with_capacity(args.len());
    for &a in args {
        let v = get_cached(cache, a)?;
        if !v.1.is_zero() {
            return Err(unevaluable(format!(
                "{name} of complex argument not yet supported in evalf"
            )));
        }
        out.push(v.0.clone());
    }
    Ok(out)
}

/// `|a| < 2^{-bits} |b|` — has the series term `a` become negligible
/// against the accumulated sum `b`?
fn negligible(a: &BigFloat, b: &BigFloat, bits: usize) -> bool {
    if a.is_zero() {
        return true;
    }
    match (a.exponent(), b.exponent()) {
        (Some(ae), Some(be)) => (be as i64 - ae as i64) > bits as i64,
        _ => false,
    }
}

/// `a > b`?
fn bf_gt(a: &BigFloat, b: &BigFloat) -> bool {
    a.cmp(b).is_some_and(|c| c > 0)
}

/// `a < b`?
fn bf_lt(a: &BigFloat, b: &BigFloat) -> bool {
    a.cmp(b).is_some_and(|c| c < 0)
}

/// A `BigFloat` that is an integer exactly, as an `i64` when it fits.
///
/// Before 0.30 a value within `10⁻¹²` of an integer counted (in `f64`),
/// and `polylog(2 + 10⁻²⁰, 999/1000)` was `Li₂(999/1000)`, wrong from its
/// 20th digit at 30 and 60 digits (the degree and order callers already
/// asked for an exact integer as well).
fn bf_as_int(x: &BigFloat, rm: RoundingMode, cc: &mut Consts) -> Result<Option<i64>, SymplexError> {
    if !(x.is_zero() || x.is_int()) {
        return Ok(None);
    }
    let r = bigfloat_to_f64(x, rm, cc)?.round();
    Ok((r.abs() < 9.0e15).then_some(r as i64))
}

/// Numeric value of the library function `f` on `args` (of the arity `f`
/// declares) inside `eval_node`.
///
/// Exhaustive over [`LibFn`].  The integer sequences and combinatorial
/// counts have no arbitrary-precision routine: `eval` folds them exactly
/// for integer arguments before `evalf` runs, and anything left is an
/// error rather than a guess.
fn eval_lib_fn(
    f: LibFn,
    args: &[ExprId],
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    match f {
        LibFn::BesselJ => eval_bessel(arb_bessel_j, "BesselJ", args, cache, prec, rm, cc),
        LibFn::BesselY => eval_bessel(arb_bessel_y, "BesselY", args, cache, prec, rm, cc),
        LibFn::BesselI => eval_bessel(arb_bessel_i, "BesselI", args, cache, prec, rm, cc),
        LibFn::BesselK => eval_bessel(arb_bessel_k, "BesselK", args, cache, prec, rm, cc),
        LibFn::Legendre => eval_orthopoly(OrthoPoly::Legendre, f, args, cache, prec, rm, cc),
        LibFn::ChebyshevT => eval_orthopoly(OrthoPoly::ChebyshevT, f, args, cache, prec, rm, cc),
        LibFn::ChebyshevU => eval_orthopoly(OrthoPoly::ChebyshevU, f, args, cache, prec, rm, cc),
        LibFn::Hermite => eval_orthopoly(OrthoPoly::Hermite, f, args, cache, prec, rm, cc),
        LibFn::Laguerre => eval_orthopoly(OrthoPoly::Laguerre, f, args, cache, prec, rm, cc),
        LibFn::Erfi
        | LibFn::ErfInv
        | LibFn::ErfcInv
        | LibFn::ExpInt
        | LibFn::Shi
        | LibFn::Chi
        | LibFn::FresnelS
        | LibFn::FresnelC
        | LibFn::LowerGamma
        | LibFn::UpperGamma
        | LibFn::DirichletEta
        | LibFn::AiryAi
        | LibFn::AiryBi
        | LibFn::AiryAiPrime
        | LibFn::AiryBiPrime
        | LibFn::EllipticK
        | LibFn::EllipticE
        | LibFn::EllipticF
        | LibFn::EllipticPi
        | LibFn::Gegenbauer
        | LibFn::Jacobi
        | LibFn::AssocLegendre
        | LibFn::AssocLaguerre
        | LibFn::BetaInc
        | LibFn::BetaIncRegularized => eval_special_09(f, args, cache, prec, rm, cc),
        LibFn::PolyLog => eval_polylog(args, cache, prec, rm, cc),
        LibFn::RisingFactorial | LibFn::FallingFactorial | LibFn::Harmonic => {
            let v = real_args(f.name(), args, cache)?;
            debug!(prec, name = f.name(), "evalf: Gamma quotient / digamma");
            let r = match f {
                LibFn::RisingFactorial => factorials::rising_factorial(&v[0], &v[1], prec, rm, cc)?,
                LibFn::FallingFactorial => {
                    factorials::falling_factorial(&v[0], &v[1], prec, rm, cc)?
                }
                _ => factorials::harmonic(&v[0], prec, rm, cc)?,
            };
            Ok((r, BigFloat::new(prec)))
        }
        LibFn::Factorial2
        | LibFn::Subfactorial
        | LibFn::Fibonacci
        | LibFn::Lucas
        | LibFn::Bernoulli
        | LibFn::Catalan
        | LibFn::Bell
        | LibFn::EulerNumber
        | LibFn::Stirling1
        | LibFn::Stirling2
        | LibFn::PartitionCount => Err(unevaluable(format!(
            "evalf has no numerical routine for '{f}' (eval folds it exactly at integer arguments)"
        ))),
        // Evaluated from its node, which carries the branch index literal.
        LibFn::LambertW => Err(unevaluable("lambertw is evaluated from its node")),
    }
}

/// `polylog(s, z)` for a real order: `arb_polylog` for a real `z ∈ [−1, 1]`,
/// `polylog::polylog_general` for a non-real `z` or `|z| > 1` (before 0.31
/// these were "not yet supported" for every order: `polylog(3/2, −3/16 −
/// 5/18·i)`, `polylog(2, 3)`, `polylog(1/3, −5)`).
fn eval_polylog(
    args: &[ExprId],
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    let s = get_cached(cache, args[0])?;
    let z = get_cached(cache, args[1])?;
    if !s.1.is_zero() {
        return polylog::polylog_complex_order(s, z, prec, rm, cc);
    }
    if polylog::off_unit_interval(z) {
        return polylog::polylog_general(&s.0, z, prec, rm, cc);
    }
    debug!(prec, "evalf: polylog on [-1, 1]");
    Ok((arb_polylog(&s.0, &z.0, prec, rm, cc)?, BigFloat::new(prec)))
}

/// `W_k(z)` of a Lambert W node (`LambertW(x)`, `lambertw(x, k)`) over ℂ,
/// on every integer branch (`evalf::lambertw`).
fn eval_lambertw_node(
    arena: &Arena,
    node: &ExprNode,
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    let (x, k) = lambertw::lambert_parts(arena, node)
        .unwrap_or_else(|| Err(unevaluable("not a Lambert W node")))?;
    let z = get_cached(cache, x)?;
    debug!(
        prec,
        k, "evalf: LambertW via Halley iteration (mpmath's starting values)"
    );
    lambertw::lambert_w(z, k, prec, rm, cc)
}

/// A Bessel function `(order, x)` of real arguments through `arb`.
fn eval_bessel(
    arb: fn(
        &BigFloat,
        &BigFloat,
        usize,
        RoundingMode,
        &mut Consts,
    ) -> Result<BigFloat, SymplexError>,
    what: &str,
    args: &[ExprId],
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    let order = get_cached(cache, args[0])?;
    let arg = get_cached(cache, args[1])?;
    if !order.1.is_zero() || !arg.1.is_zero() {
        return Err(SymplexError::Unevaluable {
            reason: "Bessel of complex argument not yet supported in evalf".into(),
        });
    }
    tracing::debug!(prec, what, "evalf: Bessel function via series/asymptotic");
    let result = arb(&order.0, &arg.0, prec, rm, cc)?;
    Ok((result, BigFloat::new(prec)))
}

/// A classical orthogonal polynomial `(n, x)` of real arguments by
/// recurrence, for a non-negative integer degree.
fn eval_orthopoly(
    kind: OrthoPoly,
    f: LibFn,
    args: &[ExprId],
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    let n_val = get_cached(cache, args[0])?;
    let x_val = get_cached(cache, args[1])?;
    if !n_val.1.is_zero() || !x_val.1.is_zero() {
        return Err(SymplexError::Unevaluable {
            reason: "orthogonal polynomial of complex arguments not supported".into(),
        });
    }
    let n_f = bigfloat_to_f64(&n_val.0, rm, cc)?;
    let n_round = n_f.round();
    // An integer exactly: before 0.29 a degree within 10⁻¹² of one was taken
    // for it, and `legendre(3 + 10⁻¹³, 1/3)` printed P₃(1/3) (wrong from the
    // 14th digit).
    if !n_val.0.is_int() || !(0.0..=1.0e7).contains(&n_round) {
        return Err(SymplexError::Unevaluable {
            reason: format!("{f}: degree must be a non-negative integer"),
        });
    }
    tracing::debug!(
        prec,
        n = n_round,
        "evalf: orthogonal polynomial via recurrence"
    );
    let result = arb_orthopoly(kind, n_round as u64, &x_val.0, prec, rm);
    Ok((result, BigFloat::new(prec)))
}

/// Dispatch for the 0.9 special functions inside `eval_node`.
///
/// Exhaustive over [`LibFn`]; the functions outside this family are an
/// error here (they are dispatched by [`eval_lib_fn`] and never arrive).
fn eval_special_09(
    f: LibFn,
    args: &[ExprId],
    cache: &FxHashMap<ExprId, Complex>,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<Complex, SymplexError> {
    let name = f.name();
    let v = real_args(name, args, cache)?;
    let real = |r: BigFloat| Ok((r, BigFloat::new(prec)));
    debug!(prec, name, "evalf: special function (0.9)");
    match f {
        LibFn::Erfi => real(arb_erfi(&v[0], prec, rm, cc)?),
        LibFn::ErfInv => real(arb_erfinv(&v[0], prec, rm, cc)?),
        LibFn::ErfcInv => real(arb_erfcinv(&v[0], prec, rm, cc)?),
        LibFn::ExpInt => real(arb_expint(&v[0], &v[1], prec, rm, cc)?),
        LibFn::Shi => real(arb_shi_chi(&v[0], true, prec, rm, cc)?),
        LibFn::Chi => {
            if v[0].is_zero() {
                return Err(unevaluable("Chi(0) is zoo"));
            }
            let chi = arb_shi_chi(&v[0].abs(), false, prec, rm, cc)?;
            if v[0].is_negative() {
                // Chi(−x) = Chi(x) + iπ
                Ok((chi, cc.pi(prec, rm).clone()))
            } else {
                real(chi)
            }
        }
        LibFn::FresnelS => real(arb_fresnel(&v[0], true, prec, rm, cc)?),
        LibFn::FresnelC => real(arb_fresnel(&v[0], false, prec, rm, cc)?),
        LibFn::LowerGamma => real(arb_lowergamma(&v[0], &v[1], prec, rm, cc)?),
        LibFn::UpperGamma => real(arb_uppergamma(&v[0], &v[1], prec, rm, cc)?),
        LibFn::DirichletEta => real(arb_dirichlet_eta(&v[0], prec, rm, cc)?),
        LibFn::AiryAi => real(arb_airy(&v[0], AiryKind::Ai, prec, rm, cc)?),
        LibFn::AiryBi => real(arb_airy(&v[0], AiryKind::Bi, prec, rm, cc)?),
        LibFn::AiryAiPrime => real(arb_airy(&v[0], AiryKind::AiPrime, prec, rm, cc)?),
        LibFn::AiryBiPrime => real(arb_airy(&v[0], AiryKind::BiPrime, prec, rm, cc)?),
        LibFn::EllipticK => real(arb_elliptic_k(&v[0], prec, rm, cc)?),
        LibFn::EllipticE => real(arb_elliptic_e(&v[0], prec, rm, cc)?),
        LibFn::EllipticF => real(arb_elliptic_f(&v[0], &v[1], prec, rm, cc)?),
        LibFn::EllipticPi => real(arb_elliptic_pi(&v[0], &v[1], prec, rm, cc)?),
        LibFn::Gegenbauer => real(arb_gegenbauer(&v[0], &v[1], &v[2], prec, rm, cc)?),
        LibFn::Jacobi => real(arb_jacobi(&v[0], &v[1], &v[2], &v[3], prec, rm, cc)?),
        LibFn::AssocLegendre => real(arb_assoc_legendre(&v[0], &v[1], &v[2], prec, rm, cc)?),
        LibFn::AssocLaguerre => real(arb_assoc_laguerre(&v[0], &v[1], &v[2], prec, rm, cc)?),
        LibFn::BetaInc | LibFn::BetaIncRegularized => real(arb_betainc(
            &v[0],
            &v[1],
            &v[2],
            &v[3],
            f == LibFn::BetaIncRegularized,
            prec,
            rm,
            cc,
        )?),
        LibFn::Factorial2
        | LibFn::Subfactorial
        | LibFn::RisingFactorial
        | LibFn::FallingFactorial
        | LibFn::Fibonacci
        | LibFn::Lucas
        | LibFn::Bernoulli
        | LibFn::Harmonic
        | LibFn::Catalan
        | LibFn::Bell
        | LibFn::EulerNumber
        | LibFn::Stirling1
        | LibFn::Stirling2
        | LibFn::PartitionCount
        | LibFn::LambertW
        | LibFn::PolyLog
        | LibFn::BesselJ
        | LibFn::BesselY
        | LibFn::BesselI
        | LibFn::BesselK
        | LibFn::Legendre
        | LibFn::ChebyshevT
        | LibFn::ChebyshevU
        | LibFn::Hermite
        | LibFn::Laguerre => Err(unevaluable(format!("cannot evaluate function '{name}'"))),
    }
}

// ── Error-function family ──────────────────────────────────────────────────────

/// `erfi(x) = (2/√π) Σ x^{2n+1}/(n!(2n+1))` (all terms of one sign, so no
/// cancellation) for `x² ≤ wp·ln 2`, otherwise the asymptotic expansion
/// `erfi(x) ~ e^{x²}/(x√π) Σ (2k−1)!!/(2x²)^k` (optimal truncation error
/// `~e^{−x²}` relative to the leading term).
fn arb_erfi(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_zero() {
        return Ok(BigFloat::new(prec));
    }
    if x.is_nan() || x.is_inf() {
        return Err(unevaluable("erfi of special float value"));
    }
    let wp = prec + 32;
    let x_f = bigfloat_to_f64(x, rm, cc)?;
    let ax = x_f.abs();
    let two = BigFloat::from_i32(2, wp);
    let sqrt_pi = cc.pi(wp, rm).clone().sqrt(wp, rm);
    let x_sq = x.mul(x, wp, rm);

    if ax * ax > (wp as f64) * std::f64::consts::LN_2 + 4.0 {
        let two_x_sq = x_sq.mul(&two, wp, rm);
        let mut sum = BigFloat::from_i32(1, wp);
        let mut term = BigFloat::from_i32(1, wp);
        let mut prev: Option<BigFloat> = None;
        for k in 1..(wp * 2 + 100) {
            let f = BigFloat::from_i128(2 * k as i128 - 1, wp);
            term = term.mul(&f, wp, rm).div(&two_x_sq, wp, rm);
            if let Some(ref p) = prev
                && bf_gt(&term, p)
            {
                break;
            }
            sum = sum.add(&term, wp, rm);
            if negligible(&term, &sum, wp) {
                break;
            }
            prev = Some(term.clone());
        }
        let e = x_sq.exp(wp, rm, cc);
        let denom = x.abs().mul(&sqrt_pi, wp, rm);
        let r = e.mul(&sum, wp, rm).div(&denom, wp, rm);
        let r = if x.is_negative() { r.neg() } else { r };
        return Ok(round_to(r, prec, rm));
    }

    let mut prod = x.clone();
    let _ = prod.set_precision(wp, rm);
    let mut sum = prod.clone();
    let max_terms = (3.0 * ax * ax) as usize + wp + 60;
    let mut converged = false;
    for n in 1..=max_terms {
        let n_bf = BigFloat::from_i128(n as i128, wp);
        prod = prod.mul(&x_sq, wp, rm).div(&n_bf, wp, rm);
        let d = BigFloat::from_i128(2 * n as i128 + 1, wp);
        let term = prod.div(&d, wp, rm);
        sum = sum.add(&term, wp, rm);
        if negligible(&term, &sum, wp) {
            converged = true;
            break;
        }
    }
    if !converged {
        return Err(series_did_not_converge("erfi", max_terms));
    }
    let r = sum.mul(&two, wp, rm).div(&sqrt_pi, wp, rm);
    Ok(round_to(r, prec, rm))
}

/// `erfc(x)` with *relative* precision `prec` for `x > 0` (absolute
/// precision, via `1 − erf`, for `x ≤ 1/2`, where nothing cancels).
///
/// * `x² log₂ e ≥ wp + 8`: the asymptotic expansion alone (relative error
///   `≈ e^{−x²}`) already delivers `wp` bits.
/// * `x ≥ 5/4`: `erfc(x) = Γ(½, x²)/√π` by Legendre's continued fraction
///   ([`uppergamma_cf`], in its regime `x² ≥ max(1, ½ + 1)`), which cancels
///   nothing.  Before 0.30 this range took `1 − erf(x)` with `x² log₂ e`
///   extra bits, a Taylor series of some `e·x²` terms at that precision
///   (`erfc(18.5)` at 300 digits: 11 ms, now 2 ms).
/// * otherwise `1 − erf(x)` with `x² log₂ e + 8` extra bits to survive the
///   cancellation (`erfc(x) ≈ e^{−x²}/(x√π)`).
fn arb_erfc(
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let wp = prec + 32;
    let x_f = bigfloat_to_f64(x, rm, cc)?;
    if x_f <= 0.5 {
        let erf = arb_erf(x, prec, rm, cc)?;
        let one = BigFloat::from_i32(1, wp);
        return Ok(round_to(one.sub(&erf, wp, rm), prec, rm));
    }
    let x_sq_bits = (x_f * x_f * std::f64::consts::LOG2_E).ceil() as usize;
    let mut xw = x.clone();
    if x_sq_bits >= wp + 8 {
        let _ = xw.set_precision(wp, rm);
        return Ok(round_to(erfc_asymptotic(&xw, wp, rm, cc), prec, rm));
    }
    if x_f >= 1.25 {
        // x² to a relative 2^−(wp + log₂ x² + 8): e^{−x²} to 2^−(wp + 8).
        let p = wp + magnitude_bits(x_f * x_f) + 8;
        let _ = xw.set_precision(p, rm);
        let x_sq = xw.mul(&xw, p, rm);
        let half = BigFloat::from_f64(0.5, 64);
        let g = uppergamma_cf(&half, &x_sq, p, rm, cc)?;
        let sqrt_pi = cc.pi(wp, rm).clone().sqrt(wp, rm);
        return Ok(round_to(g.div(&sqrt_pi, wp, rm), prec, rm));
    }
    let wp2 = wp + x_sq_bits + 8;
    let _ = xw.set_precision(wp2, rm);
    let erf = arb_erf(&xw, wp2, rm, cc)?;
    let one = BigFloat::from_i32(1, wp2);
    Ok(round_to(one.sub(&erf, wp2, rm), prec, rm))
}

/// Halley iteration for `erf(x) = y` (`solve_erfc == false`) or
/// `erfc(x) = y` (`solve_erfc == true`) from the starting point `x0`,
/// safeguarded by the bracket `[lo, hi]` that contains the root (both
/// functions are monotone): a step that leaves the bracket, or does not at
/// least halve it, is replaced by bisection, and the bracket shrinks with
/// every evaluation.  An iteration that does not converge is refused.
///
/// With `g = f/f'`, the Halley step for both equations is
/// `x ← x − g / (1 + x g)` (since `f'' = −2x f'`).
///
/// Before 0.30 there was no bracket and no convergence check: from a poor
/// start the iteration drifted to where `erfc` saturates at 2 and returned
/// its 200th iterate, `erfcinv(941/2³⁴) = −10573.05…` (truly `3.84317…`),
/// certified.
#[allow(clippy::too_many_arguments)]
fn erf_inverse_halley(
    y: &BigFloat,
    x0: f64,
    lo: f64,
    hi: f64,
    solve_erfc: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let wp = prec + 32;
    let mut yw = y.clone();
    let _ = yw.set_precision(wp, rm);
    let half_sqrt_pi = cc
        .pi(wp, rm)
        .clone()
        .sqrt(wp, rm)
        .div(&BigFloat::from_i32(2, wp), wp, rm);
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let (mut lo, mut hi) = (BigFloat::from_f64(lo, wp), BigFloat::from_f64(hi, wp));
    let mut x = BigFloat::from_f64(x0.clamp(lo_f(&lo), hi_f(&hi)), wp);
    fn lo_f(v: &BigFloat) -> f64 {
        bigfloat_to_f64_rounded(v, RoundingMode::ToEven).unwrap_or(f64::NEG_INFINITY)
    }
    fn hi_f(v: &BigFloat) -> f64 {
        bigfloat_to_f64_rounded(v, RoundingMode::ToEven).unwrap_or(f64::INFINITY)
    }
    for _ in 0..(4 * wp + 200) {
        let f = if solve_erfc {
            arb_erfc(&x, wp, rm, cc)?.sub(&yw, wp, rm)
        } else {
            arb_erf(&x, wp, rm, cc)?.sub(&yw, wp, rm)
        };
        if f.is_zero() {
            return Ok(round_to(x, prec, rm));
        }
        // erf increases, erfc decreases: the root is above x when
        // erf(x) < y or erfc(x) > y.
        let root_above = f.is_negative() != solve_erfc;
        if root_above {
            lo = x.clone();
        } else {
            hi = x.clone();
        }
        // f' = ±(2/√π) e^{−x²}  ⇒  g = f/f' = ±f (√π/2) e^{x²}
        let x_sq = x.mul(&x, wp, rm);
        let g = f
            .mul(&half_sqrt_pi, wp, rm)
            .mul(&x_sq.exp(wp, rm, cc), wp, rm);
        let g = if solve_erfc { g.neg() } else { g };
        let denom = one.add(&x.mul(&g, wp, rm), wp, rm);
        let delta = if denom.is_zero() {
            g.clone()
        } else {
            g.div(&denom, wp, rm)
        };
        // Converged to `prec + 8` bits (the working precision carries 32
        // guard bits, of which the last few are rounding noise in `f`, so
        // demanding all of them never ends: `erfinv(erf(−9))` at 60
        // digits stalled on a one-ulp bracket).
        let tol = prec + 8;
        let width = hi.sub(&lo, wp, rm);
        let candidate = x.sub(&delta, wp, rm);
        // A step below the tolerance is convergence, before the bracket is
        // consulted: below an ulp of x the candidate rounds onto x, which is
        // now an end of the bracket, and "leaving the bracket" sent a
        // converged iteration into bisection from its last bracket down to
        // the tolerance (0.29: some 260 halvings, `erfcinv(sin(1 + 10⁻¹⁵⁰)
        // − sin(1))` at 60 digits evaluated `erfc` 1,104 times).
        if negligible(&delta, &x, tol) {
            return Ok(round_to(candidate, prec, rm));
        }
        let inside = bf_gt(&candidate, &lo) && bf_lt(&candidate, &hi);
        let halves = bf_lt(&delta.abs().mul(&two, wp, rm), &width);
        if inside && halves {
            x = candidate;
            if negligible(&delta, &x, tol) {
                return Ok(round_to(x, prec, rm));
            }
        } else {
            let mid = lo.add(&hi, wp, rm).div(&two, wp, rm);
            let stuck = mid == lo || mid == hi;
            x = mid;
            if stuck || negligible(&width, &x, tol) {
                return Ok(round_to(x, prec, rm));
            }
        }
    }
    Err(SymplexError::computation_failed(
        "evalf",
        "the inverse error function iteration did not converge",
    ))
}

/// `erfinv(y)` for `|y| < 1`: Winitzki's closed-form approximation refined
/// by `f64` Newton steps, then Halley iteration on `erf` (`|y| ≤ 1/2`) or
/// on `erfc(x) = 1 − |y|` (`|y| > 1/2`, where `erf` alone would lose the
/// digits of `1 − y`).
fn arb_erfinv(
    y: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if y.is_zero() {
        return Ok(BigFloat::new(prec));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let ay = y.abs();
    let one_minus_ay = one.sub(&ay, wp, rm);
    if one_minus_ay.is_zero() || one_minus_ay.is_negative() {
        return Err(unevaluable("erfinv: argument must satisfy |y| < 1"));
    }
    // A tiny argument: erfinv(y) = (√π/2)·y·(1 + πy²/12 + …), whose
    // correction is below the working precision once |y| < 2^(−wp/2).  (The
    // bracketed iteration starts from (−½, ½) and cannot bisect down to
    // `erfinv(sech(8!)) ≈ 3·10⁻¹⁷⁵¹¹`.)
    if let Some(e) = y.exponent()
        && i64::from(e) < -(wp as i64) / 2 - 4
    {
        let half_sqrt_pi =
            cc.pi(wp, rm)
                .clone()
                .sqrt(wp, rm)
                .div(&BigFloat::from_i32(2, wp), wp, rm);
        return Ok(round_to(y.mul(&half_sqrt_pi, wp, rm), prec, rm));
    }
    let y_f = bigfloat_to_f64(y, rm, cc)?;
    let r = if y_f.abs() > 0.5 {
        arb_erfcinv_small(&one_minus_ay, prec, rm, cc)?
    } else {
        // Winitzki (a = 0.147), |relative error| < 2·10⁻³.
        let a = 0.147_f64;
        let l = (1.0 - y_f * y_f).ln();
        let t = 2.0 / (std::f64::consts::PI * a) + l / 2.0;
        let mut x0 = ((t * t - l / a).sqrt() - t).sqrt().copysign(y_f);
        for _ in 0..3 {
            let f = erf_f64(x0) - y_f;
            x0 -= f * (std::f64::consts::PI.sqrt() / 2.0) * (x0 * x0).exp();
        }
        // |y| ≤ 1/2 < erf(1/2): the root lies in (−1/2, 1/2).
        erf_inverse_halley(y, x0, -0.5, 0.5, false, prec, rm, cc)?
    };
    Ok(if y.is_negative() && !r.is_negative() && y_f.abs() > 0.5 {
        r.neg()
    } else {
        r
    })
}

/// `erfcinv(u)` for `0 < u ≤ 1/2`, Halley iteration on `erfc`.  The initial
/// guess inverts the leading asymptotic `erfc(x) ≈ e^{−x²}/(x√π)`, which
/// also covers `u` far below the `f64` range; the root lies in
/// `(0, max(√L, 1)]` with `L = −ln u` (`erfc(0) = 1 > u`, and
/// `erfc(x) < e^{−x²}/(x√π) ≤ u` there).  (0.29 refined the guess by `f64`
/// Newton steps on `1 − erf_f64(x)`, a 50-term Taylor sum whose truncation
/// near `x = 4` is `10⁻⁶`: the steps diverged.)
fn arb_erfcinv_small(
    u: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let wp = prec + 32;
    // L = −ln u  (computed in BigFloat so tiny u is fine)
    let l = u.ln(wp, rm, cc).neg();
    let l_f = bigfloat_to_f64(&l, rm, cc)?;
    let mut x0 = l_f.max(0.5).sqrt();
    for _ in 0..4 {
        // x² = L − ln(x√π)
        let v = l_f - (x0 * std::f64::consts::PI.sqrt()).ln();
        x0 = v.max(0.25).sqrt();
    }
    let hi = l_f.max(0.0).sqrt().max(1.0) * (1.0 + f64::EPSILON * 16.0);
    erf_inverse_halley(u, x0, 0.0, hi, true, prec, rm, cc)
}

/// `erfcinv(u)` for `0 < u < 2`: `erfcinv(u) = −erfcinv(2 − u)` maps to
/// `u ≤ 1`, then `erfinv(1 − u)` for `u ≥ 1/2` and the `erfc` Halley
/// iteration for smaller `u`.
fn arb_erfcinv(
    u: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    if u.is_zero() || u.is_negative() || !bf_lt(u, &two) {
        return Err(unevaluable("erfcinv: argument must satisfy 0 < u < 2"));
    }
    if bf_gt(u, &one) {
        let v = two.sub(u, wp, rm);
        return Ok(arb_erfcinv(&v, prec, rm, cc)?.neg());
    }
    let u_f = bigfloat_to_f64(u, rm, cc)?;
    if u_f >= 0.5 {
        let y = one.sub(u, wp, rm);
        return arb_erfinv(&y, prec, rm, cc);
    }
    arb_erfcinv_small(u, prec, rm, cc)
}

// ── Incomplete gamma / exponential integrals ───────────────────────────────────

/// `v > 0`: astro-float's `is_positive` is the sign bit alone, true for
/// `+0` (`expint(1 + 10⁻²⁰⁰, ⅓)` rounds its order to 1 and `s = 1 − n` to
/// `+0`, which must take the integer route, not `Γ(0)`).
fn bf_strictly_positive(v: &BigFloat) -> bool {
    v.is_positive() && !v.is_zero()
}

/// `⌈log₂ v⌉` for `v > 1`, `0` for `v ≤ 1`, 1100 for a non-finite `v`: the
/// guard bits a quantity of magnitude `v` needs for its *absolute* error to
/// stay at the unit of the working precision (an exponent `s ln x ≈ 10⁹`
/// needs 30 bits more than the relative precision of its exponential).
fn magnitude_bits(v: f64) -> usize {
    if !v.is_finite() {
        1100
    } else if v > 1.0 {
        v.log2().ceil() as usize
    } else {
        0
    }
}

/// `⌈log₂(1/s)⌉` for `0 < s < 1`, from the binary exponent (so also for an
/// `s` below the `f64` range); `0` for `s ≥ 1`.
fn inverse_bits(s: &BigFloat) -> usize {
    match s.exponent() {
        Some(e) if e < 1 => usize::try_from(1 - i64::from(e)).unwrap_or(0),
        _ => 0,
    }
}

/// Guard bits for `ln Γ(s)`, `s > 0`, whose magnitude is below
/// `s·|ln s| + s + 2` for `s ≥ 1` and `|ln s| + 2` below.
fn lngamma_bits(s: &BigFloat, s_f: f64) -> usize {
    if s_f >= 1.0 {
        magnitude_bits(s_f * s_f.ln() + s_f + 2.0)
    } else {
        magnitude_bits(inverse_bits(s) as f64 * std::f64::consts::LN_2 + 2.0)
    }
}

/// The most bits of cancellation a special function pays for with working
/// precision before it refuses: `4·wp + 1024` (a shape of `10⁻³⁰⁰` costs
/// about 1000, and is evaluated; one of `10⁻¹⁰⁰⁰` is refused at 16 and 50
/// digits — `ln Γ` by Stirling's series at 3500 bits takes seconds).
fn cancellation_cap(wp: usize) -> usize {
    wp.saturating_mul(4).saturating_add(1024)
}

/// The refusal of a special function whose cancellation exceeds
/// [`cancellation_cap`]: [`SymplexError::PrecisionExhausted`] at the digits
/// the working precision `prec` stands for (the inverse of
/// `working_precision`).  The routines below `arb_*` raise it at their own
/// working precision; [`requested_at`] restates it at the caller's.
fn special_exhausted(prec: usize) -> SymplexError {
    SymplexError::PrecisionExhausted {
        requested: u32::try_from(prec.saturating_sub(64) * 10 / 34).unwrap_or(u32::MAX),
        achieved: 0,
    }
}

/// A [`SymplexError::PrecisionExhausted`] from inside a special function,
/// restated at the precision `prec` its caller asked for (other errors
/// pass through).
fn requested_at(prec: usize) -> impl Fn(SymplexError) -> SymplexError {
    move |e| match e {
        SymplexError::PrecisionExhausted { .. } => special_exhausted(prec),
        other => other,
    }
}

/// `v` at precision `p` (a copy; the value is unchanged when `p` is larger).
fn at_precision(v: &BigFloat, p: usize, rm: RoundingMode) -> BigFloat {
    let mut w = v.clone();
    let _ = w.set_precision(p, rm);
    w
}

/// `x^s e^{−x}` for `x > 0`, as `exp(s ln x − x)` with the exponent formed
/// to an absolute error of `2^−wp` (the relative error of the result): it
/// carries the bits of its magnitude as guard.  0.28 multiplied `e^{−x}` by
/// `x^s`, two factors near the ends of the exponent range for `s ≈ x ≈ 10⁸`.
fn gamma_prefactor(
    s: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let s_f = bigfloat_to_f64(s, rm, cc)?.abs();
    let x_f = bigfloat_to_f64(x, rm, cc)?;
    // |ln x| from the binary exponent when x is outside the f64 range.
    let ln_x = x
        .exponent()
        .map_or(0.0, |e| (f64::from(e).abs() + 1.0) * std::f64::consts::LN_2);
    let wpe = wp + magnitude_bits(s_f * ln_x + x_f) + 8;
    let e = s.mul(&x.ln(wpe, rm, cc), wpe, rm).sub(x, wpe, rm);
    Ok(e.exp(wp, rm, cc))
}

/// Legendre's continued fraction for `Γ(s, x)`, `x > 0` (modified Lentz):
///
/// ```text
/// Γ(s, x) = e^{−x} x^s / (x + 1 − s − 1·(1−s)/(x + 3 − s − 2·(2−s)/(x + 5 − s − …)))
/// ```
///
/// Converges for every `x > 0` and every real `s`; it is the method of
/// choice for `x ≥ max(1, s + 1)`.  At `x = s + 1` it needs about
/// `27·s^{1/3}` steps to 266 bits (573 at `s = 10⁴`, 5779 at `s = 10⁷`) and a
/// few hundred from `x = s + 10√s` on, so the budget is
/// `40·wp + 2000 + 64·s^{1/3}` (0.28's `40·wp + 2000` fell short near
/// `s = 10⁸`), the last term at most `2·10⁶` (seconds; beyond, from
/// `s ≈ 3·10¹⁷`, the fraction is refused rather than run for minutes); the
/// fraction is evaluated with `log₂(budget) + 8` guard bits for the
/// roundings of its steps.
fn uppergamma_cf(
    s: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let s_f = bigfloat_to_f64(s, rm, cc)?;
    let max_iter = (40 * wp + 2000).saturating_add((64.0 * s_f.abs().cbrt()).min(2e6) as usize);
    let wp = wp + magnitude_bits(max_iter as f64) + 8;
    let (s, x) = (&at_precision(s, wp, rm), &at_precision(x, wp, rm));
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    // "tiny" replaces exact zeros in Lentz's algorithm.
    let mut tiny = BigFloat::from_i32(1, wp);
    tiny.set_exponent(-(4 * wp as i32));
    let mut b = x.add(&one, wp, rm).sub(s, wp, rm);
    let mut c = one.div(&tiny, wp, rm);
    let mut d = if b.is_zero() {
        one.div(&tiny, wp, rm)
    } else {
        one.div(&b, wp, rm)
    };
    let mut h = d.clone();
    let mut converged = false;
    for i in 1..=max_iter {
        let i_bf = BigFloat::from_i128(i as i128, wp);
        // a_i = −i (i − s)
        let an = i_bf.mul(&i_bf.sub(s, wp, rm), wp, rm).neg();
        b = b.add(&two, wp, rm);
        d = an.mul(&d, wp, rm).add(&b, wp, rm);
        if d.is_zero() {
            d = tiny.clone();
        }
        c = b.add(&an.div(&c, wp, rm), wp, rm);
        if c.is_zero() {
            c = tiny.clone();
        }
        d = one.div(&d, wp, rm);
        let del = d.mul(&c, wp, rm);
        h = h.mul(&del, wp, rm);
        let dev = del.sub(&one, wp, rm);
        if negligible(&dev, &one, wp) {
            converged = true;
            break;
        }
    }
    if !converged {
        return Err(SymplexError::ComputationFailed {
            operation: "evalf",
            reason: format!(
                "continued fraction for the incomplete gamma function did not converge in \
                 {max_iter} steps"
            ),
        });
    }
    let pref = gamma_prefactor(s, x, wp, rm, cc)?;
    Ok(pref.mul(&h, wp, rm))
}

/// Series for `γ(s, x) = x^s e^{−x} Σ_{k≥0} x^k / (s (s+1) … (s+k))`,
/// `s > 0`, `x ≥ 0`: positive terms, decreasing from `k ≈ x − s` on.  Near
/// `x ≈ s` about `√(2s·wp·ln 2)` of them are needed (60 000 at `s = 10⁷`),
/// each term rounding its predecessor's error once more, so the sum carries
/// `log₂(budget) + 8` guard bits.  The budget `2x + wp + 50` is capped at
/// `10⁷` terms (a refusal beyond, for shapes near `10¹³` and above).
fn lowergamma_series(
    s: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_zero() {
        return Ok(BigFloat::new(wp));
    }
    let x_f = bigfloat_to_f64(x, rm, cc)?;
    let max_terms = ((2.0 * x_f).min(1e7) as usize).saturating_add(wp + 50);
    let wp = wp + magnitude_bits(max_terms as f64) + 8;
    let (s, x) = (&at_precision(s, wp, rm), &at_precision(x, wp, rm));
    let one = BigFloat::from_i32(1, wp);
    let mut term = one.div(s, wp, rm);
    let mut sum = term.clone();
    let mut converged = false;
    for k in 1..=max_terms {
        let s_plus_k = s.add(&BigFloat::from_i128(k as i128, wp), wp, rm);
        term = term.mul(x, wp, rm).div(&s_plus_k, wp, rm);
        sum = sum.add(&term, wp, rm);
        if negligible(&term, &sum, wp) {
            converged = true;
            break;
        }
    }
    if !converged {
        return Err(series_did_not_converge("lowergamma", max_terms));
    }
    let pref = gamma_prefactor(s, x, wp, rm, cc)?;
    Ok(pref.mul(&sum, wp, rm))
}

/// `Γ(s, x)` at working precision `wp` for real `s`, `x > 0`, to a relative
/// error of about `2^−wp`:
///
/// * `x ≥ max(1, s + 1)`: the continued fraction [`uppergamma_cf`];
/// * `s > 0`, smaller `x`: `Γ(s) − γ(s, x)` ([`uppergamma_by_difference`]);
/// * `s ≤ 0`, `x < 1`: the downward recurrence ([`uppergamma_downward`]).
fn uppergamma_wp(
    s: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    // |s| below the working precision, 0 < x < 2: Γ(s, x) = E₁(x) + δ with
    // |δ| = |∫_x^∞ (t^s − 1) e^{−t}/t dt| ≤ 2|s|((ln x)²/2 + 1) and E₁(x) ≥
    // E₁(2) = 0.0489, so δ is below 2^{−wp} of the value once
    // log₂(1/|s|) ≥ wp + 8 + 2·log₂(|ln x| + 1).  (0.28 reached this limit
    // only when s underflowed f64, by taking it for the integer 0.)
    if !s.is_zero()
        && bigfloat_to_f64(x, rm, cc)? < 2.0
        && inverse_bits(&s.abs()) >= wp + 8 + 2 * magnitude_bits(ln_magnitude(x) + 1.0)
    {
        return Ok(arb_ei(&x.neg(), wp, rm, cc)?.neg());
    }
    if bf_strictly_positive(s) {
        return uppergamma_positive(s, x, wp, rm, cc);
    }
    if bigfloat_to_f64(x, rm, cc)? >= 1.0 {
        return uppergamma_cf(s, x, wp, rm, cc);
    }
    // Far left of 0 the downward recurrence takes |s| steps, while the
    // continued fraction's partial quotients are about −i/|s| for i ≪ |s|
    // and it converges in a few steps.  (0.28 ran the recurrence for any
    // s: `expint(10²⁰/3, 1/7)` overflowed `2·steps` — a panic in debug
    // builds, an endless loop in release ones.)
    if bigfloat_to_f64(s, rm, cc)? < -(DOWNWARD_MAX_STEPS as f64) {
        return uppergamma_cf(s, x, wp, rm, cc);
    }
    uppergamma_downward(s, x, wp, rm, cc)
}

/// The most steps of the downward recurrence for `Γ(s, x)`, `s ≤ 0`,
/// `x < 1`; further left the continued fraction is used.
const DOWNWARD_MAX_STEPS: usize = 256;

/// `Γ(s, x)` for `s > 0`, `x > 0`: the continued fraction for
/// `x ≥ s + 1`, [`uppergamma_by_difference`] below.
fn uppergamma_positive(
    s: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let s_f = bigfloat_to_f64(s, rm, cc)?;
    // x ≥ s + 1 exactly (in f64, s + 1 is s from 2⁵³ on, and a huge s = x
    // went to the fraction, which needs ~27·s^{1/3} steps there).
    if !bf_lt(x, &s.add(&BigFloat::from_i32(1, 64), exact_bits(s, wp), rm)) {
        return uppergamma_cf(s, x, wp, rm, cc);
    }
    uppergamma_by_difference(s, s_f, x, wp, rm, cc)
}

/// A refusal when `Γ(s) > 2^{EXPONENT_MAX + 3}` (`s ≥ 1`): the incomplete
/// gamma functions `Γ(s, x)` for `x ≤ s + 1` (at least `e^{−2}·Γ(s)`,
/// see [`uppergamma_by_difference`]) and `γ(s, x)` for `x ≥ s` (at least
/// `Γ(s)/2`, `P(s, s) > ½`) overflow the arbitrary-precision exponent
/// range.  Before 0.30 `uppergamma(10²⁰/3, 10²⁰/3)` (about `10^(6.3·10²⁰)`)
/// ran the continued fraction for two million steps (20 s in a debug
/// build) and failed to converge.
fn incomplete_gamma_overflows(s: &BigFloat, what: &str) -> Result<(), SymplexError> {
    let Ok(s_f) = bigfloat_to_f64_rounded(s, RoundingMode::ToEven) else {
        return Ok(());
    };
    if s_f.is_nan() || s_f < 1.0 {
        return Ok(());
    }
    // log₂ Γ(s) ≥ ((s − ½) ln s − s)/ln 2 (Stirling, the rest positive).
    let lg = ((s_f - 0.5) * s_f.ln() - s_f) * std::f64::consts::LOG2_E;
    if lg - 3.0 > f64::from(astro_float::EXPONENT_MAX) {
        return Err(unevaluable(format!(
            "{what}: the value (about 2^{lg:.3e}) overflows the arbitrary-precision exponent range"
        )));
    }
    Ok(())
}

/// `Γ(s, x) = Γ(s) − γ(s, x)` for `s > 0`, `x < s + 1` (the region of the
/// series).  The difference cancels `log₂(1/Q(s, x))` bits, and there
/// `Q(s, x) ≥ Q(s, s + 1)`, which is at least `e^{−2}` for `s ≥ 1` (it rises
/// from `Q(1, 2) = e^{−2}` towards ½) and at least
/// `Γ(s, 2)/Γ(s) ≥ E₁(2)·s > 0.048·s` for `s < 1` (`t^{s−1} ≥ 1/t` on
/// `[2, ∞)`, and `Γ(s) ≤ 1/s`; mpmath finds `min Q(s, s + 1)/s = e^{−2}`
/// over `s ≤ 1`): at most `log₂(1/min(1, s)) + 5` bits, added to the working
/// precision up front, with the bits of `ln Γ(s)` for the relative accuracy
/// of `Γ(s)` itself.  0.28 assumed `Q` was never small here and added
/// guard bits for `x` instead — `1.44·x` of them (10⁷ bits, a hang, at
/// `x ≈ 7·10⁶`) and none for a small `s`: `uppergamma(10⁻¹⁰⁰, ½)` came out
/// `0.5649…`, truly `0.5597…`.
fn uppergamma_by_difference(
    s: &BigFloat,
    s_f: f64,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if inverse_bits(s) > cancellation_cap(wp) {
        return Err(special_exhausted(wp));
    }
    let wp2 = wp + 8 + inverse_bits(s) + lngamma_bits(s, s_f);
    let sw = at_precision(s, wp2, rm);
    let xw = at_precision(x, wp2, rm);
    let g = arb_gamma_real(&sw, wp2, rm, cc)?;
    let lower = lowergamma_series(&sw, &xw, wp2, rm, cc)?;
    Ok(round_to(g.sub(&lower, wp2, rm), wp, rm))
}

/// `Γ(s, x)` for `s ≤ 0`, `0 < x < 1`: from `Γ(s₀, x)` with
/// `s₀ = s + n ∈ (0, 1)` (or from `Γ(0, x) = E₁(x)` for an integer
/// `s = −n`) by `n` downward steps `Γ(σ − 1, x) = (t − Γ(σ, x))/(1 − σ)`,
/// `t = x^{σ−1}e^{−x}`.  Each step subtracts two positive numbers, and for
/// `x ≤ 1`
///
/// ```text
/// t − Γ(σ, x) = t·∫₀^∞ (1 − (1 + u/x)^{σ−1}) e^{−u} du ≥ 0.40·min(1, 1 − σ)·t
/// ```
///
/// (convexity in the exponent, and `∫₀^∞ u/(1 + u) e^{−u} du = 1 − e·E₁(1)
/// = 0.4037`), so a step loses at most `log₂(1/min(1, 1 − σ)) + 1.4` bits —
/// many in the first step when `s` sits just below an integer.  The losses
/// are measured as they occur and the evaluation is repeated with a larger
/// reserve when they exceed it.  0.28 reserved 16 bits per step and took an
/// `s` within `10⁻¹²` of an integer for that integer:
/// `expint(3 + 10⁻¹⁴, ⅓)` was wrong from its 14th digit,
/// `uppergamma(−2 + 10⁻¹⁵, ½)` from its 16th.
fn uppergamma_downward(
    s: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let s_f = bigfloat_to_f64(s, rm, cc)?;
    let integer = s.is_int();
    let steps = if integer {
        (-s_f).round() as usize
    } else {
        (-s_f).ceil() as usize
    };
    let cap = cancellation_cap(wp);
    let mut reserve = steps.saturating_mul(2).saturating_add(32);
    loop {
        let wp2 = wp + reserve;
        let sw = at_precision(s, wp2, rm);
        let xw = at_precision(x, wp2, rm);
        // Base point: Γ(0, x) = E₁(x) = −Ei(−x) for an integer s; otherwise
        // Γ(s₀, x) with s₀ = s + steps ∈ (0, 1).
        let (mut cur_s, mut val) = if integer {
            (BigFloat::new(wp2), arb_ei(&xw.neg(), wp2, rm, cc)?.neg())
        } else {
            let s0 = sw.add(&BigFloat::from_i128(steps as i128, wp2), wp2, rm);
            let v = uppergamma_positive(&s0, &xw, wp2, rm, cc)?;
            (s0, v)
        };
        let one = BigFloat::from_i32(1, wp2);
        let mut lost = 0usize;
        for _ in 0..steps {
            let next_s = cur_s.sub(&one, wp2, rm);
            let t = gamma_prefactor(&next_s, &xw, wp2, rm, cc)?;
            let diff = t.sub(&val, wp2, rm);
            match (t.exponent(), diff.exponent()) {
                (Some(et), Some(ed)) if bf_strictly_positive(&diff) => {
                    lost += usize::try_from(i64::from(et) - i64::from(ed)).unwrap_or(0);
                }
                _ => {
                    lost = wp2;
                    break;
                }
            }
            val = diff.div(&next_s.neg(), wp2, rm);
            cur_s = next_s;
        }
        if lost + 16 <= reserve {
            return Ok(round_to(val, wp, rm));
        }
        if reserve >= cap {
            return Err(special_exhausted(wp));
        }
        reserve = (lost + 32).max(2 * reserve).min(cap);
    }
}

/// Upper incomplete gamma `Γ(s, x)` for real `s`, `x ≥ 0`.
fn arb_uppergamma(
    s: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || s.is_nan() || x.is_inf_neg() || s.is_inf() {
        return Err(unevaluable("uppergamma of special float value"));
    }
    if x.is_inf_pos() {
        return Ok(BigFloat::new(prec));
    }
    if x.is_negative() {
        return Err(unevaluable(
            "uppergamma of negative argument not yet supported in evalf",
        ));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, 64);
    if bf_strictly_positive(s) && !bf_gt(x, &s.add(&one, exact_bits(s, wp), rm)) {
        incomplete_gamma_overflows(s, "uppergamma")?;
    }
    if x.is_zero() {
        if !bf_strictly_positive(s) {
            return Err(unevaluable("uppergamma(s, 0) diverges for s ≤ 0"));
        }
        let s_f = bigfloat_to_f64(s, rm, cc)?;
        let wp = wp + lngamma_bits(s, s_f);
        return Ok(round_to(arb_gamma_real(s, wp, rm, cc)?, prec, rm));
    }
    let r = uppergamma_wp(s, x, wp, rm, cc).map_err(requested_at(prec))?;
    Ok(round_to(r, prec, rm))
}

/// Lower incomplete gamma `γ(s, x)` for real `s > 0`, `x ≥ 0`: the series
/// for `x < s + 1`, `Γ(s) − Γ(s, x)` beyond, where `P(s, x) ≥ P(s, s + 1)
/// > 0.51` (mpmath, over `s` from `10⁻²⁷` to `10³`, rising towards ½ + … for
/// larger `s`) and at most a bit cancels.
fn arb_lowergamma(
    s: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || s.is_nan() || s.is_inf() || x.is_inf_neg() {
        return Err(unevaluable("lowergamma of special float value"));
    }
    if !bf_strictly_positive(s) {
        return Err(unevaluable(
            "lowergamma requires s > 0 for numerical evaluation",
        ));
    }
    if x.is_negative() {
        return Err(unevaluable(
            "lowergamma of negative argument not yet supported in evalf",
        ));
    }
    let s_f = bigfloat_to_f64(s, rm, cc)?;
    let wp = prec + 32;
    if x.is_inf_pos() {
        let wp = wp + lngamma_bits(s, s_f);
        return Ok(round_to(arb_gamma_real(s, wp, rm, cc)?, prec, rm));
    }
    if !bf_lt(x, s) {
        incomplete_gamma_overflows(s, "lowergamma")?;
    }
    if bf_lt(x, &s.add(&BigFloat::from_i32(1, 64), exact_bits(s, wp), rm)) {
        let r = lowergamma_series(s, x, wp, rm, cc).map_err(requested_at(prec))?;
        return Ok(round_to(r, prec, rm));
    }
    let wp = wp + 4 + lngamma_bits(s, s_f);
    let g = arb_gamma_real(s, wp, rm, cc)?;
    let upper = uppergamma_cf(s, x, wp, rm, cc)?;
    Ok(round_to(g.sub(&upper, wp, rm), prec, rm))
}

/// Generalised exponential integral `E_n(x) = x^{n−1} Γ(1−n, x)` for real
/// `n` and `x > 0` (`E_n(0) = 1/(n−1)` for `n > 1`).
fn arb_expint(
    n: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || n.is_nan() || n.is_inf() {
        return Err(unevaluable("expint of special float value"));
    }
    if x.is_inf_pos() {
        return Ok(BigFloat::new(prec));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    if x.is_zero() {
        let n_minus_1 = n.sub(&one, wp, rm);
        if !n_minus_1.is_positive() {
            return Err(unevaluable("expint(n, 0) diverges for n ≤ 1"));
        }
        return Ok(round_to(one.div(&n_minus_1, wp, rm), prec, rm));
    }
    if x.is_negative() {
        return Err(unevaluable(
            "expint of negative argument is complex; not yet supported in evalf",
        ));
    }
    let s = one.sub(n, wp, rm);
    let g = uppergamma_wp(&s, x, wp, rm, cc).map_err(requested_at(prec))?;
    let x_pow = bf_pow(x, &n.sub(&one, wp, rm), wp, rm, cc);
    Ok(round_to(x_pow.mul(&g, wp, rm), prec, rm))
}

/// `Shi(x)` (`want_shi`) or `Chi(x)` for `x > 0` (`Shi` is odd and is
/// returned for any real `x`).
///
/// * `|x| ≤ 40`: `Shi(x) = Σ x^{2k+1}/((2k+1)(2k+1)!)`,
///   `Chi(x) = γ + ln x + Σ_{k≥1} x^{2k}/((2k)(2k)!)` — all terms positive.
/// * larger `|x|`: `Shi = (Ei(x) − Ei(−x))/2`, `Chi = (Ei(x) + Ei(−x))/2`.
fn arb_shi_chi(
    x: &BigFloat,
    want_shi: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || x.is_inf() {
        return Err(unevaluable("Shi/Chi of special float value"));
    }
    if x.is_zero() {
        return if want_shi {
            Ok(BigFloat::new(prec))
        } else {
            Err(unevaluable("Chi(0) is zoo"))
        };
    }
    let wp = prec + 32;
    let ax = x.abs();
    let x_f = bigfloat_to_f64(&ax, rm, cc)?;
    let r = if x_f > 40.0 {
        let ei_pos = arb_ei(&ax, wp, rm, cc)?;
        let ei_neg = arb_ei(&ax.neg(), wp, rm, cc)?;
        let two = BigFloat::from_i32(2, wp);
        if want_shi {
            ei_pos.sub(&ei_neg, wp, rm).div(&two, wp, rm)
        } else {
            ei_pos.add(&ei_neg, wp, rm).div(&two, wp, rm)
        }
    } else {
        let mut xw = ax.clone();
        let _ = xw.set_precision(wp, rm);
        let x2 = xw.mul(&xw, wp, rm);
        let max_terms = (x_f * 1.5) as usize + wp + 40;
        let name = if want_shi { "Shi" } else { "Chi" };
        let mut converged = false;
        let series = if want_shi {
            // t_k = x^{2k+1}/(2k+1)!
            let mut t = xw.clone();
            let mut sum = BigFloat::new(wp);
            for k in 0..max_terms {
                if k > 0 {
                    let d = BigFloat::from_i128((2 * k as i128) * (2 * k as i128 + 1), wp);
                    t = t.mul(&x2, wp, rm).div(&d, wp, rm);
                }
                let term = t.div(&BigFloat::from_i128(2 * k as i128 + 1, wp), wp, rm);
                sum = sum.add(&term, wp, rm);
                if negligible(&term, &sum, wp) {
                    converged = true;
                    break;
                }
            }
            sum
        } else {
            let gamma = arb_euler_gamma(wp, rm, cc)?;
            let ln_x = xw.ln(wp, rm, cc);
            let mut u = BigFloat::from_i32(1, wp); // x^{2k}/(2k)!
            let mut sum = BigFloat::new(wp);
            for k in 1..max_terms {
                let d = BigFloat::from_i128((2 * k as i128 - 1) * (2 * k as i128), wp);
                u = u.mul(&x2, wp, rm).div(&d, wp, rm);
                let term = u.div(&BigFloat::from_i128(2 * k as i128, wp), wp, rm);
                sum = sum.add(&term, wp, rm);
                if negligible(&term, &sum, wp) {
                    converged = true;
                    break;
                }
            }
            gamma.add(&ln_x, wp, rm).add(&sum, wp, rm)
        };
        if !converged {
            return Err(series_did_not_converge(name, max_terms));
        }
        series
    };
    let r = if want_shi && x.is_negative() {
        r.neg()
    } else {
        r
    };
    Ok(round_to(r, prec, rm))
}

/// Fresnel integrals `S(x)` (`want_s`) and `C(x)` for real `x` (both odd).
///
/// * `πx²/2 ≤ wp·ln 2`: Maclaurin series
///   `S = Σ (−1)^k (π/2)^{2k+1} x^{4k+3}/((2k+1)!(4k+3))`,
///   `C = Σ (−1)^k (π/2)^{2k} x^{4k+1}/((2k)!(4k+1))`, with guard bits for
///   the `e^{πx²/2}` cancellation.
/// * beyond: DLMF 7.12 auxiliary functions
///   `S = 1/2 − f cos(πx²/2) − g sin(πx²/2)`, `C = 1/2 + f sin(πx²/2) − g cos(πx²/2)`,
///   `f ~ (1/πx) Σ (−1)^m (4m−1)!!/(πx²)^{2m}`, `g ~ (1/πx) Σ (−1)^m (4m+1)!!/(πx²)^{2m+1}`
///   (optimal truncation error `~e^{−πx²/2}`).
fn arb_fresnel(
    x: &BigFloat,
    want_s: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || x.is_inf() {
        return Err(unevaluable("Fresnel integral of special float value"));
    }
    if x.is_zero() {
        return Ok(BigFloat::new(prec));
    }
    let base_wp = prec + 32;
    let ax = x.abs();
    let x_f = bigfloat_to_f64(&ax, rm, cc)?;
    let arg_f = std::f64::consts::FRAC_PI_2 * x_f * x_f;

    // `x = 2^(e−1)… 2^e`: the auxiliary functions are `~1/(πx)`, and the
    // phase `πx²/2` has `2e` bits before the point.
    let e = usize::try_from(ax.exponent().map_or(0, i64::from).max(0)).unwrap_or(0);
    let r = if e > base_wp + 2 {
        // `f cos + g sin` is below `2^−wp` next to 1/2: before 0.30 the
        // phase was reduced anyway (`fresnels(erfi(335))`, `x ≈ 2^161900`,
        // asked for π to 323,800 bits and hung).
        BigFloat::from_f64(0.5, base_wp)
    } else if arg_f > (base_wp as f64) * std::f64::consts::LN_2 {
        let wp = base_wp;
        let mut xw = ax.clone();
        let _ = xw.set_precision(wp, rm);
        let one = BigFloat::from_i32(1, wp);
        let pi = cc.pi(wp, rm).clone();
        let pi_x2 = pi.mul(&xw, wp, rm).mul(&xw, wp, rm);
        let inv = one.div(&pi_x2, wp, rm); // 1/(πx²)
        let inv2 = inv.mul(&inv, wp, rm);
        // f-series: (4m−1)!!/(πx²)^{2m}; g-series: (4m+1)!!/(πx²)^{2m+1}
        let mut tf = one.clone();
        let mut tg = inv.clone();
        let mut f_sum = BigFloat::new(wp);
        let mut g_sum = BigFloat::new(wp);
        let mut prev: Option<BigFloat> = None;
        for m in 0..(wp * 2 + 100) {
            if m > 0 {
                // (4m−1)!!/(4m−5)!! = (4m−3)(4m−1); (4m+1)!!/(4m−3)!! = (4m−1)(4m+1)
                let a = BigFloat::from_i128((4 * m as i128 - 3) * (4 * m as i128 - 1), wp);
                let b = BigFloat::from_i128((4 * m as i128 - 1) * (4 * m as i128 + 1), wp);
                tf = tf.mul(&a, wp, rm).mul(&inv2, wp, rm);
                tg = tg.mul(&b, wp, rm).mul(&inv2, wp, rm);
            }
            if let Some(ref p) = prev
                && bf_gt(&tf, p)
            {
                break;
            }
            if m % 2 == 0 {
                f_sum = f_sum.add(&tf, wp, rm);
                g_sum = g_sum.add(&tg, wp, rm);
            } else {
                f_sum = f_sum.sub(&tf, wp, rm);
                g_sum = g_sum.sub(&tg, wp, rm);
            }
            if negligible(&tf, &one, wp) {
                break;
            }
            prev = Some(tf.clone());
        }
        let pi_x = pi.mul(&xw, wp, rm);
        let f = f_sum.div(&pi_x, wp, rm);
        let g = g_sum.div(&pi_x, wp, rm);
        let two = BigFloat::from_i32(2, wp);
        // The phase to an absolute `2^−wp`: `2e` more bits.  Before 0.30 it
        // was formed at `wp` bits, an absolute error of `2^(2e−wp)` times
        // the amplitude `2^−e` — wrong digits once `e` passed the guard
        // bits: `fresnels(10⁴⁵)` at 60 digits ended `…816212`, truly
        // `…816209`.
        let wt = wp + 2 * e;
        let mut xt = ax.clone();
        let _ = xt.set_precision(wt, rm);
        let theta =
            cc.pi(wt, rm)
                .mul(&xt, wt, rm)
                .mul(&xt, wt, rm)
                .div(&BigFloat::from_i32(2, wt), wt, rm);
        let s = theta.sin(wp, rm, cc);
        let c = theta.cos(wp, rm, cc);
        let half = one.div(&two, wp, rm);
        if want_s {
            half.sub(&f.mul(&c, wp, rm), wp, rm)
                .sub(&g.mul(&s, wp, rm), wp, rm)
        } else {
            half.add(&f.mul(&s, wp, rm), wp, rm)
                .sub(&g.mul(&c, wp, rm), wp, rm)
        }
    } else {
        let wp = base_wp + (arg_f * std::f64::consts::LOG2_E).ceil() as usize + 16;
        let mut xw = ax.clone();
        let _ = xw.set_precision(wp, rm);
        let pi = cc.pi(wp, rm).clone();
        let two = BigFloat::from_i32(2, wp);
        let half_pi = pi.div(&two, wp, rm);
        let x2 = xw.mul(&xw, wp, rm);
        // u = (π/2) x²;  terms: S_k = (−1)^k u^{2k+1} x /((2k+1)! (4k+3)),
        //                          C_k = (−1)^k u^{2k} x /((2k)! (4k+1))
        let u = half_pi.mul(&x2, wp, rm);
        let u2 = u.mul(&u, wp, rm);
        let mut t = if want_s {
            u.mul(&xw, wp, rm)
        } else {
            xw.clone()
        };
        let mut sum = BigFloat::new(wp);
        let max_terms = (arg_f * 2.0) as usize + wp + 40;
        let mut converged = false;
        for k in 0..max_terms {
            if k > 0 {
                let d = if want_s {
                    BigFloat::from_i128((2 * k as i128) * (2 * k as i128 + 1), wp)
                } else {
                    BigFloat::from_i128((2 * k as i128 - 1) * (2 * k as i128), wp)
                };
                t = t.mul(&u2, wp, rm).div(&d, wp, rm);
            }
            let div = BigFloat::from_i128(4 * k as i128 + if want_s { 3 } else { 1 }, wp);
            let term = t.div(&div, wp, rm);
            if k % 2 == 0 {
                sum = sum.add(&term, wp, rm);
            } else {
                sum = sum.sub(&term, wp, rm);
            }
            if negligible(&term, &sum, wp) {
                converged = true;
                break;
            }
        }
        if !converged {
            let name = if want_s { "fresnels" } else { "fresnelc" };
            return Err(series_did_not_converge(name, max_terms));
        }
        sum
    };
    let r = if x.is_negative() { r.neg() } else { r };
    Ok(round_to(r, prec, rm))
}

// ── Incomplete beta ───────────────────────────────────────────────────────────────

/// `|ln v|` bounded from the binary exponent of `v > 0` (so for any
/// magnitude, and never below `ln 2`).
fn ln_magnitude(v: &BigFloat) -> f64 {
    v.exponent()
        .map_or(0.0, |e| (f64::from(e).abs() + 1.0) * std::f64::consts::LN_2)
}

/// A bound on `|ln Γ(s)|` for `s > 0` (see [`lngamma_bits`]).
fn lngamma_magnitude(s: &BigFloat, s_f: f64) -> f64 {
    if s_f >= 1.0 {
        s_f * s_f.ln() + s_f + 2.0
    } else {
        ln_magnitude(s) + 2.0
    }
}

/// `ln B(a, b) = ln Γ(a) + ln Γ(b) − ln Γ(a + b)` for `a, b > 0` to an
/// absolute error of about `2^−wp`: each `ln Γ` carries the bits of the
/// largest magnitude as guard (they are `≈ 1.7·10⁹` for shapes near `10⁸`
/// and cancel to the size of `ln B`), which also covers the rounding of
/// `a + b`.
fn ln_beta_wp(
    a: &BigFloat,
    b: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let a_f = bigfloat_to_f64(a, rm, cc)?;
    let b_f = bigfloat_to_f64(b, rm, cc)?;
    let ab_f = a_f + b_f;
    let mag = lngamma_magnitude(a, a_f)
        .max(lngamma_magnitude(b, b_f))
        .max(ab_f * ab_f.ln().abs() + ab_f + 2.0);
    let p = wp + magnitude_bits(mag) + 8;
    let a_plus_b = a.add(b, p, rm);
    let la = stirling_log_gamma(a, p, rm, cc)?;
    let lb = stirling_log_gamma(b, p, rm, cc)?;
    let lab = stirling_log_gamma(&a_plus_b, p, rm, cc)?;
    Ok(la.add(&lb, p, rm).sub(&lab, p, rm))
}

/// `B(a, b) = Γ(a)Γ(b)/Γ(a+b)` at working precision `wp` for `a, b > 0`, as
/// `exp(ln B(a, b))`: the three gamma values need not be representable
/// (`Γ(10⁸)` is beyond the exponent range, `B(10⁸, 10⁸) = 2^{−2·10⁸}` is
/// not).
fn beta_wp(
    a: &BigFloat,
    b: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    Ok(ln_beta_wp(a, b, wp, rm, cc)?.exp(wp, rm, cc))
}

/// The continued fraction of the regularised incomplete beta function
/// (DLMF 8.17.22; evaluated by the modified Lentz algorithm of Thompson &
/// Barnett, J. Comput. Phys. 64 (1986) 490):
///
/// ```text
/// I_x(a, b) = x^a (1−x)^b / (a B(a, b)) · 1/(1 + d₁/(1 + d₂/(1 + …)))
/// d_{2m}   =  m (b−m) x / ((a+2m−1)(a+2m))
/// d_{2m+1} = −(a+m)(a+b+m) x / ((a+2m)(a+2m+1))
/// ```
///
/// Returns the fraction `1/(1 + d₁/…)` only (the prefactor is applied by
/// the caller).  Converges quickly for `x < (a+1)/(a+b+2)`.  Evaluated with
/// `log₂(2·budget) + 8` guard bits for the roundings of its steps; the
/// shape-dependent part of the budget, `10·√(a + b)`, is capped at `2·10⁶`
/// steps (seconds; shapes near `10¹⁴` still converge within it, and
/// beyond it the fraction is refused rather than run for minutes).
fn betainc_cf(
    a: &BigFloat,
    b: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let ab_f = bigfloat_to_f64(&a.add(b, 64, rm), rm, cc)?;
    // The number of steps grows like √(max(a, b)) before the linear
    // convergence phase; budget generously.
    let max_iter = (40 * wp + 2000).saturating_add((10.0 * ab_f.abs().sqrt()).min(2e6) as usize);
    let wp = wp + magnitude_bits(2.0 * max_iter as f64) + 8;
    let (a, b, x) = (
        &at_precision(a, wp, rm),
        &at_precision(b, wp, rm),
        &at_precision(x, wp, rm),
    );
    let one = BigFloat::from_i32(1, wp);
    // "tiny" replaces exact zeros in Lentz's algorithm.
    let mut tiny = BigFloat::from_i32(1, wp);
    tiny.set_exponent(-(4 * wp as i32));
    let qab = a.add(b, wp, rm);
    let qap = a.add(&one, wp, rm);
    let qam = a.sub(&one, wp, rm);
    let mut c = one.clone();
    let mut d = one.sub(&qab.mul(x, wp, rm).div(&qap, wp, rm), wp, rm);
    if d.is_zero() {
        d = tiny.clone();
    }
    d = one.div(&d, wp, rm);
    let mut h = d.clone();
    let mut converged = false;
    // One Lentz step with partial numerator `aa`; returns `del = d·c`.
    let step = |aa: &BigFloat, c: &mut BigFloat, d: &mut BigFloat| -> BigFloat {
        *d = one.add(&aa.mul(d, wp, rm), wp, rm);
        if d.is_zero() {
            *d = tiny.clone();
        }
        *c = one.add(&aa.div(c, wp, rm), wp, rm);
        if c.is_zero() {
            *c = tiny.clone();
        }
        *d = one.div(d, wp, rm);
        d.mul(c, wp, rm)
    };
    for m in 1..=max_iter {
        let m_bf = BigFloat::from_i128(m as i128, wp);
        let m2_bf = BigFloat::from_i128(2 * m as i128, wp);
        // Even step: d_{2m} = m (b−m) x / ((a+2m−1)(a+2m)).
        let num = m_bf.mul(&b.sub(&m_bf, wp, rm), wp, rm).mul(x, wp, rm);
        let den = qam.add(&m2_bf, wp, rm).mul(&a.add(&m2_bf, wp, rm), wp, rm);
        let aa = num.div(&den, wp, rm);
        let del = step(&aa, &mut c, &mut d);
        h = h.mul(&del, wp, rm);
        // Odd step: d_{2m+1} = −(a+m)(a+b+m) x / ((a+2m)(a+2m+1)).
        let num = a
            .add(&m_bf, wp, rm)
            .mul(&qab.add(&m_bf, wp, rm), wp, rm)
            .mul(x, wp, rm)
            .neg();
        let den = a.add(&m2_bf, wp, rm).mul(&qap.add(&m2_bf, wp, rm), wp, rm);
        let aa = num.div(&den, wp, rm);
        let del = step(&aa, &mut c, &mut d);
        h = h.mul(&del, wp, rm);
        let dev = del.sub(&one, wp, rm);
        if negligible(&dev, &one, wp) {
            converged = true;
            break;
        }
    }
    if !converged {
        return Err(SymplexError::ComputationFailed {
            operation: "evalf",
            reason: format!(
                "continued fraction for the incomplete beta function did not converge in \
                 {max_iter} steps"
            ),
        });
    }
    Ok(h)
}

/// `x^a y^b / (a B(a, b))` for `0 < x < 1`, `y = 1 − x`, as one
/// exponential of `a ln x + b ln y − ln a − ln B(a, b)`: the exponent is
/// formed with the bits of its magnitude as guard, so that its absolute
/// error — the relative error of the result — is `2^−wp`, and `ln B` comes
/// from [`ln_beta_wp`].  0.28 formed `x^a`, `y^b` and
/// `B(a, b) = Γ(a)Γ(b)/Γ(a + b)` separately: `Γ(10⁸)` is beyond the exponent
/// range, and `betainc_regularized(10⁸ + ⅓, 10⁸ + 1/7, 0, ½)` was refused.
fn betainc_prefactor(
    a: &BigFloat,
    b: &BigFloat,
    x: &BigFloat,
    y: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let a_f = bigfloat_to_f64(a, rm, cc)?;
    let b_f = bigfloat_to_f64(b, rm, cc)?;
    let ab_f = a_f + b_f;
    let mag = a_f * ln_magnitude(x)
        + b_f * ln_magnitude(y)
        + ln_magnitude(a)
        + lngamma_magnitude(a, a_f)
        + lngamma_magnitude(b, b_f)
        + ab_f * ab_f.ln().abs()
        + ab_f
        + 2.0;
    let p = wp + magnitude_bits(mag) + 8;
    let e = a
        .mul(&x.ln(p, rm, cc), p, rm)
        .add(&b.mul(&y.ln(p, rm, cc), p, rm), p, rm)
        .sub(&a.ln(p, rm, cc), p, rm)
        .sub(&ln_beta_wp(a, b, p, rm, cc)?, p, rm);
    Ok(e.exp(wp, rm, cc))
}

/// `I_x(a, b)` for `x ≤ (a+1)/(a+b+2)` (`one_minus_x = 1 − x` is passed in
/// so that it is exact): continued fraction times `x^a (1−x)^b / (a B(a, b))`.
fn betainc_reg_direct(
    a: &BigFloat,
    b: &BigFloat,
    x: &BigFloat,
    one_minus_x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let h = betainc_cf(a, b, x, wp, rm, cc)?;
    let pref = betainc_prefactor(a, b, x, one_minus_x, wp, rm, cc)?;
    Ok(pref.mul(&h, wp, rm))
}

/// The switch point `(a+1)/(a+b+2)` of the continued fraction: below it
/// `I_x(a, b)` is computed directly, above it `I_{1−x}(b, a)`.
fn betainc_switch_point(a: &BigFloat, b: &BigFloat, wp: usize, rm: RoundingMode) -> BigFloat {
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let a_plus_1 = a.add(&one, wp, rm);
    let a_plus_b_plus_2 = a.add(b, wp, rm).add(&two, wp, rm);
    a_plus_1.div(&a_plus_b_plus_2, wp, rm)
}

/// `(I_x(a, b), I_{1−x}(b, a))` for `a, b > 0`, `0 < x < 1`: both tails of
/// the regularised incomplete beta function, each to a relative error of
/// about `2^−wp`.
///
/// The continued fraction converges fast on the side of the smaller
/// argument: it gives `I_x(a, b)` directly for `x ≤ (a+1)/(a+b+2)` and
/// `I_{1−x}(b, a)` above, and the other tail is `1 −` it.  That difference
/// cancels when the directly computed tail is close to 1: a small first
/// shape piles the mass against 0 (`I_{1/10}(10⁻⁶⁰, ⅓) = 1 − 4.8·10⁻⁶⁰`).
/// 0.28 assumed at most a bit was lost there and printed garbage as
/// certified digits: `betainc_regularized(⅓, 10⁻¹⁰⁰, 0, 9/10)` was
/// `1.28·10⁻⁸²`, truly `4.79·10⁻¹⁰⁰`.  The loss is measured instead: the
/// direct tail `d`, computed to a relative `2^−p`, leaves `1 − d` with an
/// absolute error of `2^−p`, i.e. `p − log₂(1/(1 − d))` correct bits, and
/// `d` is recomputed at a precision covering the loss (a first shape
/// `s < 1` costs about `log₂(1/s)` bits, which are added up front), up to
/// [`cancellation_cap`].
fn betainc_tails_wp(
    a: &BigFloat,
    b: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, BigFloat), SymplexError> {
    let direct_lower = !bf_gt(x, &betainc_switch_point(a, b, wp, rm));
    let first = if direct_lower { a } else { b };
    let ab_bits = magnitude_bits(bigfloat_to_f64(&a.add(b, 64, rm), rm, cc)?);
    let cap = cancellation_cap(wp);
    // The loss is about log₂(1/s) for a first shape s < 1 (less by at most
    // log₂|ln x|): beyond the cap, refuse before computing at that precision.
    let mut extra = 16 + inverse_bits(first);
    if extra > cap {
        return Err(special_exhausted(wp));
    }
    loop {
        let p = wp + extra;
        // 1 − x: exact for x ≥ ½ (the argument's own bits); rounded far
        // below the unit of `b ln y` otherwise.
        let py = p + 64 + ab_bits;
        let y = BigFloat::from_i32(1, py).sub(x, py, rm);
        let d = if direct_lower {
            betainc_reg_direct(a, b, x, &y, p, rm, cc)?
        } else {
            betainc_reg_direct(b, a, &y, x, p, rm, cc)?
        };
        let c = BigFloat::from_i32(1, p).sub(&d, p, rm);
        let lost = match c.exponent() {
            Some(e) if bf_strictly_positive(&c) => usize::try_from(1 - i64::from(e)).unwrap_or(0),
            _ => p,
        };
        if lost + 8 <= extra {
            let (d, c) = (round_to(d, wp, rm), round_to(c, wp, rm));
            return Ok(if direct_lower { (d, c) } else { (c, d) });
        }
        if extra >= cap {
            return Err(special_exhausted(wp));
        }
        extra = (lost + 16).max(2 * extra).min(cap);
    }
}

/// Both tails at a limit `t ∈ [0, 1]` (exact at the ends).
fn betainc_tails_at(
    a: &BigFloat,
    b: &BigFloat,
    t: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, BigFloat), SymplexError> {
    let one = BigFloat::from_i32(1, wp);
    if t.is_zero() {
        return Ok((BigFloat::new(wp), one));
    }
    if t.cmp(&one) == Some(0) {
        return Ok((one, BigFloat::new(wp)));
    }
    betainc_tails_wp(a, b, t, wp, rm, cc)
}

/// `I_{hi}(a, b) − I_{lo}(a, b)` for `0 ≤ lo < hi ≤ 1` at working precision
/// `wp`, together with the number of bits lost to cancellation in the
/// subtraction (`wp` when the difference vanished entirely).
///
/// Both tails are known at each limit ([`betainc_tails_at`]), so the
/// difference is `L(hi) − L(lo) = U(lo) − U(hi)` with `L(t) = I_t(a, b)`
/// and `U(t) = I_{1−t}(b, a)`, and the form whose larger term is the smaller
/// is taken: no `1 − …` is formed here, so a lower tail (`lo = 0`) or an
/// upper one (`hi = 1`) is a single directly computed tail, and limits near
/// 1 keep their relative accuracy.  What remains is the cancellation of
/// close limits, which the caller covers with precision.
fn betainc_reg_diff_wp(
    a: &BigFloat,
    b: &BigFloat,
    lo: &BigFloat,
    hi: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, usize), SymplexError> {
    let (l_lo, u_lo) = betainc_tails_at(a, b, lo, wp, rm, cc)?;
    let (l_hi, u_hi) = betainc_tails_at(a, b, hi, wp, rm, cc)?;
    let (p, q) = if bf_gt(&l_hi, &u_lo) {
        (u_lo, u_hi)
    } else {
        (l_hi, l_lo)
    };
    let diff = p.sub(&q, wp, rm);
    let lost = match (p.exponent(), q.exponent(), diff.exponent()) {
        _ if q.is_zero() => 0,
        _ if !bf_strictly_positive(&diff) => wp,
        (Some(ep), Some(eq), Some(ed)) => {
            usize::try_from(i64::from(ep.max(eq)) - i64::from(ed)).unwrap_or(0)
        }
        _ => 0,
    };
    Ok((diff, lost))
}

/// Generalised incomplete beta `B_{(x1, x2)}(a, b) = ∫_{x1}^{x2} t^{a−1}(1−t)^{b−1} dt`
/// (or `I_{(x1, x2)}(a, b) = B_{(x1, x2)}(a, b)/B(a, b)` when `regularized`)
/// for real `a, b > 0` and `0 ≤ x1, x2 ≤ 1`.
///
/// Computed as `I_{x2}(a, b) − I_{x1}(a, b)` ([`betainc_reg_diff_wp`]); when
/// the two values nearly cancel (`x1 ≈ x2`) the working precision is raised
/// by the number of bits lost and the difference recomputed, until the
/// loss is covered — or refused beyond [`cancellation_cap`].  0.28 returned
/// its third attempt whatever it had lost.
#[allow(clippy::too_many_arguments)]
fn arb_betainc(
    a: &BigFloat,
    b: &BigFloat,
    x1: &BigFloat,
    x2: &BigFloat,
    regularized: bool,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let name = if regularized {
        "betainc_regularized"
    } else {
        "betainc"
    };
    if [a, b, x1, x2].iter().any(|v| v.is_nan() || v.is_inf()) {
        return Err(unevaluable(format!("{name} of special float value")));
    }
    if !bf_strictly_positive(a) || !bf_strictly_positive(b) {
        return Err(unevaluable(format!(
            "{name} requires a, b > 0 for numerical evaluation"
        )));
    }
    let one = BigFloat::from_i32(1, prec);
    if [x1, x2].iter().any(|x| x.is_negative() || bf_gt(x, &one)) {
        return Err(unevaluable(format!(
            "{name}: the limits x1, x2 must lie in [0, 1] for numerical evaluation"
        )));
    }
    // Orient the limits so that lo < hi; the sign is restored at the end.
    let (lo, hi, negate) = match x1.cmp(x2) {
        Some(c) if c < 0 => (x1, x2, false),
        Some(c) if c > 0 => (x2, x1, true),
        _ => return Ok(BigFloat::new(prec)),
    };
    let cap = prec + cancellation_cap(prec);
    let mut wp = prec + 32;
    let mut diff = loop {
        let (d, lost) =
            betainc_reg_diff_wp(a, b, lo, hi, wp, rm, cc).map_err(requested_at(prec))?;
        // Done once the guard bits cover the cancellation (16 to spare).
        if lost + prec + 16 <= wp {
            break d;
        }
        if wp >= cap {
            return Err(special_exhausted(prec));
        }
        wp = (prec + 32 + lost).min(cap);
    };
    if !regularized {
        let beta = beta_wp(a, b, wp, rm, cc)?;
        diff = diff.mul(&beta, wp, rm);
    }
    if negate {
        diff = diff.neg();
    }
    Ok(round_to(diff, prec, rm))
}

// ── Polylogarithm / Dirichlet eta ───────────────────────────────────────────────

/// `ζ(m)` for an integer `m ≤ 0`, exactly: `ζ(0) = −1/2`,
/// `ζ(−k) = −B_{k+1}/(k+1)`.
fn zeta_nonpositive_int(m: i64, wp: usize, rm: RoundingMode) -> BigFloat {
    if m == 0 {
        return BigFloat::from_f64(-0.5, wp);
    }
    let k = (-m) as usize;
    let b = crate::base::bernoulli::bernoulli(k + 1);
    if b.is_zero() {
        return BigFloat::new(wp);
    }
    let v = -b / Ratio::from_integer(BigInt::from(k as i64 + 1));
    ratio_to_bigfloat(&v, wp, rm)
}

/// `k^s` for integer `k ≥ 1`.
fn int_pow_s(
    k: usize,
    s: &BigFloat,
    s_int: Option<i64>,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> BigFloat {
    let kb = BigFloat::from_i128(k as i128, wp);
    match s_int {
        Some(n) if n >= 0 => kb.powi(n as usize, wp, rm),
        Some(n) => BigFloat::from_i32(1, wp).div(&kb.powi((-n) as usize, wp, rm), wp, rm),
        None => bf_pow(&kb, s, wp, rm, cc),
    }
}

/// Number of terms after which `|z|^k k^{−s}` has certainly fallen below
/// `2^{−wp}·|z|` (the first term): about `wp·ln 2 / (−ln|z|)` for `s ≥ 0`;
/// for `s < 0` the factor `k^{|s|}` first grows the terms (peak near
/// `k = |s|/(−ln|z|)`), so the bound is found by doubling from there.
fn polylog_series_terms(s_f: f64, z_f: f64, wp: usize) -> usize {
    if !(z_f > 0.0 && z_f < 1.0) {
        return wp * 2 + 60;
    }
    let a = -z_f.ln(); // > 0
    let target = (wp as f64) * std::f64::consts::LN_2 + a;
    let mut k = target / a;
    let m = (-s_f).max(0.0);
    if m > 0.0 {
        // k·a − m·ln k increases for k > m/a.
        k = k.max(m / a);
        for _ in 0..200 {
            if k * a - m * k.ln() >= target {
                break;
            }
            k *= 2.0;
        }
    }
    (k.ceil() as usize).saturating_add(20)
}

/// Direct series `Li_s(z) = Σ_{k≥1} z^k/k^s` for `|z| < 1` (used up to
/// [`polylog_series_limit`]); see [`polylog_series_terms`] for the term
/// bound.  For `z < 0` and `s < 0` the alternating terms can be far
/// larger than the sum; the bits lost to that cancellation are measured
/// and the sum recomputed once with that many guard bits.
fn polylog_series(
    s: &BigFloat,
    s_int: Option<i64>,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let (sum, lost) = polylog_series_raw(s, s_int, z, wp, rm, cc)?;
    // A few bits (an alternating series with s ≥ 0 loses about one) are
    // covered by the caller's guard bits.
    if lost <= 4 {
        return Ok(sum);
    }
    let wp2 = wp + lost + 8;
    let mut sw = s.clone();
    let _ = sw.set_precision(wp2, rm);
    let mut zw = z.clone();
    let _ = zw.set_precision(wp2, rm);
    let (sum, _) = polylog_series_raw(&sw, s_int, &zw, wp2, rm, cc)?;
    Ok(round_to(sum, wp, rm))
}

/// One pass of [`polylog_series`] at working precision `wp`; also returns
/// the number of bits by which the largest term exceeded the final sum.
fn polylog_series_raw(
    s: &BigFloat,
    s_int: Option<i64>,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, usize), SymplexError> {
    let z_f = bigfloat_to_f64(z, rm, cc).unwrap_or(0.5).abs();
    let s_f = bigfloat_to_f64(s, rm, cc).unwrap_or(0.0);
    let max_terms = polylog_series_terms(s_f, z_f, wp);
    let mut zk = z.clone();
    let mut sum = BigFloat::new(wp);
    let mut max_exp: Option<i64> = None;
    let mut converged = false;
    for k in 1..=max_terms {
        if k > 1 {
            zk = zk.mul(z, wp, rm);
        }
        let term = zk.div(&int_pow_s(k, s, s_int, wp, rm, cc), wp, rm);
        if let Some(e) = term.exponent() {
            max_exp = Some(max_exp.map_or(e as i64, |m| m.max(e as i64)));
        }
        sum = sum.add(&term, wp, rm);
        if negligible(&term, &sum, wp) {
            converged = true;
            break;
        }
    }
    if !converged {
        return Err(series_did_not_converge("polylog", max_terms));
    }
    let lost = match (max_exp, sum.exponent()) {
        (Some(m), Some(se)) if m > se as i64 => (m - se as i64) as usize,
        _ => 0,
    };
    Ok((sum, lost))
}

/// The largest `n` of `Li₋ₙ(z)` by its finite sum ([`polylog_nonpositive`],
/// `polylog::nonpositive`): the row of `n + 1` Stirling numbers takes
/// `O(n²)` operations on integers of up to `n·log₂ n` bits (0.1 s at 1000).
const MAX_NONPOSITIVE_ORDER: u64 = 1000;

thread_local! {
    /// The last row of [`stirling2_row`]: the precision loops of `Li₋ₙ` ask
    /// for the same row at every pass.
    static STIRLING_ROW: std::cell::RefCell<Option<(u64, std::rc::Rc<Vec<BigInt>>)>> =
        const { std::cell::RefCell::new(None) };
}

/// The Stirling numbers of the second kind `S(m, j)`, `j = 0 … m`: one row
/// of the triangle `S(i, j) = j·S(i−1, j) + S(i−1, j−1)`, the integers
/// `crate::domains::combinatorics::stirling2` gives one at a time by the
/// same triangle (`O(m·j)` each).  Before 0.34 the row of `Li₋ₙ` took them
/// one at a time, `O(n³)`: `polylog(−601, 4/13)` 18 s, `polylog(−1401,
/// 4/13)` minutes.  Refused beyond [`MAX_NONPOSITIVE_ORDER`]` + 1`.
fn stirling2_row(m: u64) -> Result<std::rc::Rc<Vec<BigInt>>, SymplexError> {
    if m > MAX_NONPOSITIVE_ORDER + 1 {
        return Err(SymplexError::NotImplemented(format!(
            "polylog of an order below -{MAX_NONPOSITIVE_ORDER} (a finite sum of {m} terms with \
             Stirling numbers)"
        )));
    }
    if let Some(row) = STIRLING_ROW.with(|c| {
        c.borrow()
            .as_ref()
            .filter(|(k, _)| *k == m)
            .map(|(_, r)| std::rc::Rc::clone(r))
    }) {
        return Ok(row);
    }
    let mu = m as usize;
    let mut row = vec![BigInt::zero(); mu + 1];
    row[0] = BigInt::from(1);
    for i in 1..=mu {
        for j in (1..=i).rev() {
            let (lower, upper) = row.split_at_mut(j);
            upper[0] *= j as u64;
            upper[0] += &lower[j - 1];
        }
        row[0] = BigInt::zero();
    }
    let row = std::rc::Rc::new(row);
    STIRLING_ROW.with(|c| *c.borrow_mut() = Some((m, std::rc::Rc::clone(&row))));
    Ok(row)
}

/// `Li_{−n}(z)` for integer `n ≥ 0` and any real `z ≠ 1`:
/// `Σ_{k=0}^{n} k! S(n+1, k+1) (z/(1−z))^{k+1}`, at `wp` bits, and `log₂` of
/// its largest term.  For `z < 0` the terms alternate and cancel (see
/// [`polylog_nonpositive_measured`]).
fn polylog_nonpositive(
    n: usize,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
) -> Result<(BigFloat, f64), SymplexError> {
    let one = BigFloat::from_i32(1, wp);
    let one_minus_z = one.sub(z, wp, rm);
    if one_minus_z.is_zero() {
        return Err(unevaluable("polylog(s, 1) diverges for s ≤ 1"));
    }
    let w = z.div(&one_minus_z, wp, rm);
    let row = stirling2_row(n as u64 + 1)?;
    let mut k_fact = BigInt::from(1);
    let mut w_pow = w.clone();
    let mut sum = BigFloat::new(wp);
    let mut largest = f64::NEG_INFINITY;
    for k in 0..=n {
        if k > 0 {
            k_fact *= BigInt::from(k as u64);
            w_pow = w_pow.mul(&w, wp, rm);
        }
        let c = ratio_to_bigfloat(&Ratio::from_integer(&k_fact * &row[k + 1]), wp, rm);
        let term = c.mul(&w_pow, wp, rm);
        if let Some(e) = term.exponent().filter(|_| !term.is_zero()) {
            largest = largest.max(f64::from(e));
        }
        sum = sum.add(&term, wp, rm);
    }
    Ok((sum, largest))
}

/// [`polylog_nonpositive`] to `prec` bits: the loss of the alternating sum
/// of a negative `z` (the largest term over the value) measured and made up
/// with more bits, up to [`cancellation_cap`]; the first pass, at `prec +
/// 32` bits, as before 0.34.  Before 0.34 it went unmeasured:
/// `polylog(−200, −1/2)` was `2.03·10²⁹⁶`, truly `−5.15·10²⁷²`.
fn polylog_nonpositive_measured(
    n: usize,
    z: &BigFloat,
    prec: usize,
    rm: RoundingMode,
) -> Result<BigFloat, SymplexError> {
    let cap = cancellation_cap(prec);
    let mut extra = 32;
    loop {
        let (value, largest) = polylog_nonpositive(n, z, prec + extra, rm)?;
        let lost = match value.exponent() {
            Some(e) if !value.is_zero() && largest.is_finite() => {
                (largest - f64::from(e)).max(0.0).ceil() as usize
            }
            _ if largest.is_finite() => prec + extra,
            _ => 0,
        };
        if lost + 16 <= extra {
            return Ok(round_to(value, prec, rm));
        }
        if extra >= cap || lost + 16 > cap {
            return Err(special_exhausted(prec));
        }
        extra = (lost + 32).max(2 * extra).min(cap);
    }
}

/// `Li_s(z)` for `1/2 < z < 1` via the expansion in `μ = ln z` (`|μ| < 2π`):
///
/// * integer `s = n ≥ 1`:
///   `Li_n(e^μ) = μ^{n−1}/(n−1)! (H_{n−1} − ln(−μ)) + Σ_{k≥0, k≠n−1} ζ(n−k) μ^k/k!`
/// * non-integer `s`: `Li_s(e^μ) = Γ(1−s)(−μ)^{s−1} + Σ_{k≥0} ζ(s−k) μ^k/k!`
///
/// For `s` next to an integer `n` the first term and the term `k = n − 1`
/// have opposite poles (`Γ(1 − s)` and `ζ(s − n + 1)`, about `1/|s − n|`)
/// that cancel: the loss, the largest term over the sum, is measured and
/// the expansion repeated with that many more bits (up to
/// [`cancellation_cap`]).  Before 0.30 it went unmeasured, and
/// `polylog(2 + 10⁻²⁰, 999/1000)` was wrong from its 20th digit at 60
/// digits (`polylog(1 + 10⁻³⁰, 95/100)` from its 29th).
fn polylog_near_one(
    s: &BigFloat,
    s_int: Option<i64>,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    // The caller's `wp` carries 32 guard bits; a loss within 24 of them
    // costs nothing.
    let cap = cancellation_cap(wp);
    let mut extra = 0usize;
    loop {
        let p = wp + extra;
        let (sum, largest) = polylog_near_one_at(s, s_int, z, p, rm, cc)?;
        let lost = match (largest, sum.exponent()) {
            (Some(l), Some(e)) if !sum.is_zero() => usize::try_from(l - i64::from(e)).unwrap_or(0),
            (Some(_), _) => p,
            _ => 0,
        };
        if lost <= extra + 24 {
            return Ok(round_to(sum, wp, rm));
        }
        if extra >= cap {
            return Err(special_exhausted(wp));
        }
        extra = (lost + 16).max(2 * extra).min(cap);
    }
}

/// `ζ(σ₁), ζ(σ₁ − 1), ζ(σ₁ − 2), …` for a non-integer `σ₁ < −1`: the
/// terms of the `μ`-expansion of [`polylog_near_one`] left of 0, where each
/// used to cost a whole `ζ` evaluation (a `Γ` by Stirling's series and a
/// Borwein sum with its exact coefficients rebuilt: `polylog(1/3, −1 +
/// 10⁻¹²)` spent 0.35 s on some 25 of them at 60 digits).  By the
/// functional equation `ζ(σ) = 2^σ π^{σ−1} sin(πσ/2) Γ(1−σ) ζ(1−σ)`
/// every factor follows from the previous one: `2^σ π^{σ−1}` divided by
/// `2π`, the sine a quarter period on, `Γ(t)` times `t` (`t = 1 − σ`), and
/// `ζ(t) = η(t)/(1 − 2^{1−t})` for `t ≥ 2` by one Borwein sum (Algorithm 2
/// of the paper cited at [`arb_eta_borwein`]) whose coefficients are built
/// once and whose powers `m^{−t}` are divided by `m` from one `t` to the
/// next.  The working precision carries 16 guard bits for the roundings
/// that accumulate over the steps.
struct ZetaLeft {
    wp: usize,
    /// `2^σ π^{σ−1}`.
    scale: BigFloat,
    inv_two_pi: BigFloat,
    /// `sin(πσ/2)`, `cos(πσ/2)`.
    sin: BigFloat,
    cos: BigFloat,
    /// `Γ(t)` and `t = 1 − σ`.
    gamma: BigFloat,
    t: BigFloat,
    /// Borwein's `(−1)^k (d_k − d_n)/d_n`, `k < n`.
    coeffs: Vec<BigFloat>,
    /// `m^{−t}`, `m = 1 … n` (index `m − 1`).
    powers: Vec<BigFloat>,
    /// `1/m`.
    inverses: Vec<BigFloat>,
    /// `2^{1−t}`.
    two_pow: BigFloat,
}

impl ZetaLeft {
    fn new(
        sigma: &BigFloat,
        wp: usize,
        rm: RoundingMode,
        cc: &mut Consts,
    ) -> Result<Self, SymplexError> {
        let wp = wp + 16;
        let one = BigFloat::from_i32(1, 64);
        let t = one.sub(sigma, exact_bits(sigma, wp), rm);
        let pi = cc.pi(wp, rm).clone();
        let two = BigFloat::from_i32(2, 64);
        let scale = bf_pow(&two, sigma, wp, rm, cc).mul(
            &bf_pow(&pi, &sigma.sub(&one, wp, rm), wp, rm, cc),
            wp,
            rm,
        );
        let half_pi_sigma = pi.mul(sigma, wp, rm).div(&two, wp, rm);
        let gamma = arb_gamma_real(&t, wp, rm, cc)?;
        let n =
            ((wp as f64) * std::f64::consts::LN_2 / (3.0 + 8f64.sqrt()).ln()).ceil() as usize + 4;
        let mut d: Vec<Ratio<BigInt>> = Vec::with_capacity(n + 1);
        let mut acc = Ratio::<BigInt>::zero();
        let mut term = Ratio::from_integer(BigInt::from(1));
        for i in 0..=n {
            if i > 0 {
                let numer = BigInt::from((n + i - 1) as u64)
                    * BigInt::from(4u64)
                    * BigInt::from((n - i + 1) as u64);
                let denom = BigInt::from((2 * i - 1) as u64) * BigInt::from((2 * i) as u64);
                term *= Ratio::new(numer, denom);
            }
            acc += &term;
            d.push(acc.clone());
        }
        let coeffs = (0..n)
            .map(|k| {
                let c = ratio_to_bigfloat(&((&d[k] - &d[n]) / &d[n]), wp, rm);
                if k % 2 == 0 { c } else { c.neg() }
            })
            .collect();
        // m^{−t}: a power for each prime, products for the composites.
        let neg_t = t.neg();
        let mut spf = vec![0usize; n + 1];
        let mut powers: Vec<BigFloat> = Vec::with_capacity(n);
        for m in 1..=n {
            if m >= 2 && spf[m] == 0 {
                for multiple in (m..=n).step_by(m) {
                    if spf[multiple] == 0 {
                        spf[multiple] = m;
                    }
                }
            }
            let v = if m == 1 {
                BigFloat::from_i32(1, wp)
            } else if spf[m] == m {
                bf_pow(&BigFloat::from_u64(m as u64, 64), &neg_t, wp, rm, cc)
            } else {
                powers[spf[m] - 1].mul(&powers[m / spf[m] - 1], wp, rm)
            };
            powers.push(v);
        }
        let inverses = (1..=n)
            .map(|m| one.div(&BigFloat::from_u64(m as u64, 64), wp, rm))
            .collect();
        let two_pow = bf_pow(&two, &one.sub(&t, wp, rm), wp, rm, cc);
        Ok(ZetaLeft {
            wp,
            scale,
            inv_two_pi: one.div(&pi.mul(&two, wp, rm), wp, rm),
            sin: half_pi_sigma.sin(wp, rm, cc),
            cos: half_pi_sigma.cos(wp, rm, cc),
            gamma,
            t,
            coeffs,
            powers,
            inverses,
            two_pow,
        })
    }

    /// `ζ(σ)` at the current `σ`, then a step to `σ − 1`.
    fn next(&mut self, rm: RoundingMode) -> BigFloat {
        let wp = self.wp;
        let mut eta = BigFloat::new(wp);
        for (c, p) in self.coeffs.iter().zip(self.powers.iter()) {
            eta = eta.add(&c.mul(p, wp, rm), wp, rm);
        }
        let one = BigFloat::from_i32(1, 64);
        let zeta_t = eta.neg().div(&one.sub(&self.two_pow, wp, rm), wp, rm);
        let value = self
            .scale
            .mul(&self.sin, wp, rm)
            .mul(&self.gamma, wp, rm)
            .mul(&zeta_t, wp, rm);
        // σ → σ − 1, t → t + 1.
        self.scale = self.scale.mul(&self.inv_two_pi, wp, rm);
        let (s, c) = (self.cos.neg(), self.sin.clone());
        self.sin = s;
        self.cos = c;
        self.gamma = self.gamma.mul(&self.t, wp, rm);
        self.t = self.t.add(&one, wp, rm);
        for (p, inv) in self.powers.iter_mut().zip(self.inverses.iter()) {
            *p = p.mul(inv, wp, rm);
        }
        self.two_pow = self.two_pow.div(&BigFloat::from_i32(2, 64), wp, rm);
        value
    }
}

/// One evaluation of [`polylog_near_one`] at working precision `wp`, and
/// the binary exponent of the largest term summed.
fn polylog_near_one_at(
    s: &BigFloat,
    s_int: Option<i64>,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, Option<i64>), SymplexError> {
    let mut largest: Option<i64> = None;
    let mut note = |v: &BigFloat| {
        if !v.is_zero()
            && let Some(e) = v.exponent()
        {
            largest = Some(largest.map_or(i64::from(e), |m| m.max(i64::from(e))));
        }
    };
    let one = BigFloat::from_i32(1, wp);
    let mu = z.ln(wp, rm, cc); // negative
    let neg_mu = mu.neg();
    // The terms decay like (|μ|/2π)^k (|ζ(−m)| ~ m!/(2π)^m), |μ| < ln 2.
    let max_terms = wp * 2 + 100;
    let not_converged = || series_did_not_converge("polylog", max_terms);
    let mut sum = BigFloat::new(wp);
    let mut mu_pow_over_fact = one.clone(); // μ^k/k!
    // ζ vanishes at the negative even integers, so a single negligible
    // term proves nothing: stop only after two in a row.
    let mut small_run = 0u8;
    let mut converged = false;
    match s_int {
        Some(n) if n >= 1 => {
            let n = n as usize;
            for k in 0..max_terms {
                if k > 0 {
                    mu_pow_over_fact = mu_pow_over_fact.mul(&mu, wp, rm).div(
                        &BigFloat::from_i128(k as i128, wp),
                        wp,
                        rm,
                    );
                }
                if k + 1 == n {
                    // μ^{n−1}/(n−1)! (H_{n−1} − ln(−μ))
                    let mut h = BigFloat::new(wp);
                    for j in 1..n {
                        h = h.add(
                            &one.div(&BigFloat::from_i128(j as i128, wp), wp, rm),
                            wp,
                            rm,
                        );
                    }
                    let ln_neg_mu = neg_mu.ln(wp, rm, cc);
                    let t = mu_pow_over_fact.mul(&h.sub(&ln_neg_mu, wp, rm), wp, rm);
                    note(&t);
                    sum = sum.add(&t, wp, rm);
                    continue;
                }
                let arg = n as i64 - k as i64;
                let zeta = if arg <= 0 {
                    zeta_nonpositive_int(arg, wp, rm)
                } else {
                    arb_zeta(&BigFloat::from_i128(arg as i128, wp), wp, rm, cc)?
                };
                let term = zeta.mul(&mu_pow_over_fact, wp, rm);
                note(&term);
                sum = sum.add(&term, wp, rm);
                if k >= n {
                    if negligible(&term, &sum, wp) {
                        small_run += 1;
                        if small_run >= 2 {
                            converged = true;
                            break;
                        }
                    } else {
                        small_run = 0;
                    }
                }
            }
            if !converged {
                return Err(not_converged());
            }
            Ok((sum, largest))
        }
        _ => {
            // `1 − s` exact, as `s − k` below: next to an integer the poles of
            // `Γ(1 − s)` and `ζ(s − n + 1)` cancel only for the same `s` (a
            // rounded `1 − s` moves `1/|s − n|` by its rounding over
            // `(s − n)²`).
            let one_minus_s = BigFloat::from_i32(1, 64).sub(s, exact_bits(s, wp), rm);
            let g = arb_gamma_real(&one_minus_s, wp, rm, cc)?;
            let s_minus_1 = s.sub(&one, wp, rm);
            let lead = g.mul(&bf_pow(&neg_mu, &s_minus_1, wp, rm, cc), wp, rm);
            note(&lead);
            let minus_one = BigFloat::from_i32(-1, 64);
            let mut left: Option<ZetaLeft> = None;
            for k in 0..max_terms {
                if k > 0 {
                    mu_pow_over_fact = mu_pow_over_fact.mul(&mu, wp, rm).div(
                        &BigFloat::from_i128(k as i128, wp),
                        wp,
                        rm,
                    );
                }
                let arg = s.sub(&BigFloat::from_i128(k as i128, wp), exact_bits(s, wp), rm);
                // Left of −1 from the sequence (see [`ZetaLeft`]).
                let zeta = if left.is_some() || bf_lt(&arg, &minus_one) {
                    if left.is_none() {
                        left = Some(ZetaLeft::new(&arg, wp, rm, cc)?);
                    }
                    match left.as_mut() {
                        Some(l) => l.next(rm),
                        None => arb_zeta(&arg, wp, rm, cc)?,
                    }
                } else {
                    arb_zeta(&arg, wp, rm, cc)?
                };
                let term = zeta.mul(&mu_pow_over_fact, wp, rm);
                note(&term);
                sum = sum.add(&term, wp, rm);
                if k >= 2 {
                    if negligible(&term, &sum, wp) {
                        small_run += 1;
                        if small_run >= 2 {
                            converged = true;
                            break;
                        }
                    } else {
                        small_run = 0;
                    }
                }
            }
            if !converged {
                return Err(not_converged());
            }
            Ok((lead.add(&sum, wp, rm), largest))
        }
    }
}

/// Largest `|z|` for which the direct series is used.  For integer `s` the
/// `μ`-expansion is cheap (Bernoulli numbers), so it takes over at `1/2`;
/// for non-integer `s` its terms `ζ(s − k)` come from one incremental
/// sequence left of −1 ([`ZetaLeft`]), a few multiplications per Borwein
/// term, and it takes over at `3/4`, where the direct series needs
/// `wp·ln 2/ln(4/3)` terms of a non-integer power each.  (Before 0.30 every
/// `ζ(s − k)` was a full evaluation and the direct series ran up to `0.95`:
/// 1,800 powers for `polylog(1/3, −95/100)` at 60 digits, 0.57 s.)
fn polylog_series_limit(s_int: Option<i64>, wp: usize) -> BigFloat {
    if s_int.is_some() {
        BigFloat::from_f64(0.5, wp)
    } else {
        BigFloat::from_f64(0.75, wp)
    }
}

/// `Li_s(z)` for `0 < |z| < 1`.
fn polylog_unit_interval(
    s: &BigFloat,
    s_int: Option<i64>,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let limit = polylog_series_limit(s_int, wp);
    let az = z.abs();
    // A large order: `k^(−s) < 2^(−wp)` from `k = 16` on, the direct series
    // ends after a few terms wherever `abs(z) < 1`.  Before 0.37 the expansion
    // in `ln z` took over beyond `abs(z) = ½` and summed `ζ(s − k)` for every
    // `k < s`: `polylog(1038, −9/10)` was refused ("did not converge").
    let large = bigfloat_to_f64_rounded(s, rm).is_ok_and(|v| v >= wp as f64 / 4.0 + 8.0);
    if large || !bf_gt(&az, &limit) {
        return polylog_series(s, s_int, z, wp, rm, cc);
    }
    if z.is_negative() {
        // Li_s(−x) = 2^{1−s} Li_s(x²) − Li_s(x).  The difference cancels
        // where Li_s(−x) is small next to its terms (next to a zero of
        // η(s) = −Li_s(−1), s ≈ −2, −4, …): the loss is measured and the
        // difference formed again with that many more bits.
        let cap = cancellation_cap(wp);
        let mut extra = 0usize;
        loop {
            let p = wp + extra;
            let one = BigFloat::from_i32(1, p);
            let x2 = az.mul(&az, 2 * p, rm);
            let a = polylog_unit_interval(s, s_int, &x2, p, rm, cc)?;
            let b = polylog_near_one(s, s_int, &az, p, rm, cc)?;
            let two = BigFloat::from_i32(2, p);
            let one_minus_s = one.sub(s, exact_bits(s, p), rm);
            let scale = bf_pow(&two, &one_minus_s, p, rm, cc);
            let first = scale.mul(&a, p, rm);
            let r = first.sub(&b, p, rm);
            let largest = first.exponent().max(b.exponent()).map_or(0, i64::from);
            let lost = match r.exponent() {
                Some(e) if !r.is_zero() => usize::try_from(largest - i64::from(e)).unwrap_or(0),
                _ => p,
            };
            if lost <= extra + 24 {
                return Ok(round_to(r, wp, rm));
            }
            if extra >= cap {
                return Err(special_exhausted(wp));
            }
            extra = (lost + 16).max(2 * extra).min(cap);
        }
    }
    polylog_near_one(s, s_int, z, wp, rm, cc)
}

/// Polylogarithm `Li_s(z)` for real `s` and real `−1 ≤ z ≤ 1` (any real
/// `z ≠ 1` when `s` is a non-positive integer, where `Li_s` is rational).
/// A non-real `z` or `|z| > 1` is `polylog::polylog_general`.
fn arb_polylog(
    s: &BigFloat,
    z: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if s.is_nan() || z.is_nan() || s.is_inf() || z.is_inf() {
        return Err(unevaluable("polylog of special float value"));
    }
    if z.is_zero() {
        return Ok(BigFloat::new(prec));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let s_int = bf_as_int(s, rm, cc)?;
    if let Some(n) = s_int
        && n <= 0
    {
        // Beyond the Stirling sum: the poles of `polylog::nonpositive_poles`,
        // their cancellation measured by `polylog_general` (up to its
        // largest order; beyond, the Stirling sum refuses).
        if n.unsigned_abs() > MAX_NONPOSITIVE_ORDER && n.unsigned_abs() <= 1_000_000 {
            let v = polylog::polylog_general(s, &(z.clone(), BigFloat::new(prec)), prec, rm, cc)?;
            return Ok(round_to(v.0, prec, rm));
        }
        return polylog_nonpositive_measured(n.unsigned_abs() as usize, z, prec, rm);
    }
    let az = z.abs();
    if bf_gt(&az, &one) {
        return Err(unevaluable(
            "polylog outside the unit disc not yet supported in evalf",
        ));
    }
    if az.sub(&one, wp, rm).is_zero() {
        // z = ±1
        if z.is_negative() {
            // Li_s(−1) = −η(s), entire in s.
            let eta = arb_eta(s, wp, rm, cc)?;
            return Ok(round_to(eta.neg(), prec, rm));
        }
        if !bf_gt(s, &one) {
            return Err(unevaluable("polylog(s, 1) diverges for s ≤ 1"));
        }
        let zeta = arb_zeta(s, wp, rm, cc)?;
        return Ok(round_to(zeta, prec, rm));
    }
    let r = polylog_unit_interval(s, s_int, z, wp, rm, cc)?;
    Ok(round_to(r, prec, rm))
}

/// Dirichlet eta `η(s)` at working precision `wp` for real `s`: Borwein's
/// alternating sum ([`arb_eta_borwein`]) for `s > 0` — `η` is entire, so
/// nothing special happens near `s = 1` (`η(1) = ln 2`) — and
/// `(1 − 2^{1−s}) ζ(s)` for `s ≤ 0`.
fn arb_eta(
    s: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    // Strictly: `+0` has the sign bit of a positive number, and Borwein's sum at
    // `s = 0` is not `η(0) = 1/2` (before 0.30 `dirichlet_eta` of an argument
    // that cancelled to `+0` printed `0.4913903202446295`).
    if bf_strictly_positive(s) {
        return arb_eta_borwein(s, wp, rm, cc);
    }
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let one_minus_s = one.sub(s, wp, rm);
    let coeff = one.sub(&bf_pow(&two, &one_minus_s, wp, rm, cc), wp, rm);
    let zeta = arb_zeta(s, wp, rm, cc)?;
    Ok(coeff.mul(&zeta, wp, rm))
}

/// Dirichlet eta `η(s)` (see [`arb_eta`]), with `η(+∞) = 1`.
fn arb_dirichlet_eta(
    s: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if s.is_nan() || s.is_inf_neg() {
        return Err(unevaluable("dirichlet_eta of special float value"));
    }
    if s.is_inf_pos() {
        return Ok(BigFloat::from_i32(1, prec));
    }
    let wp = prec + 32;
    let mut sw = s.clone();
    let _ = sw.set_precision(wp, rm);
    Ok(round_to(arb_eta(&sw, wp, rm, cc)?, prec, rm))
}

// ── Airy functions ─────────────────────────────────────────────────────────────

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum AiryKind {
    Ai,
    Bi,
    AiPrime,
    BiPrime,
}

/// Airy functions for real `x`.
///
/// * `|x|^{3/2} ≤ (3/4)·wp·ln 2`: Maclaurin series (DLMF 9.4.1–9.4.4)
///   `Ai = c₁ f − c₂ g`, `Bi = √3 (c₁ f + c₂ g)` with
///   `f = Σ x^{3k}/∏_{j≤k}(3j−1)(3j)`, `g = Σ x^{3k+1}/∏_{j≤k}(3j)(3j+1)`,
///   `c₁ = 3^{−2/3}/Γ(2/3)`, `c₂ = 3^{−1/3}/Γ(1/3)`; the working precision
///   carries `(4/3)|x|^{3/2} log₂ e` guard bits for the cancellation.
/// * beyond, with `ζ = (2/3)|x|^{3/2}`: the asymptotic expansions
///   DLMF 9.7.5–9.7.12 (`u_k`, `v_k = −(6k+1)/(6k−1) u_k`), whose optimal
///   truncation error is `~e^{−2ζ}`.
fn arb_airy(
    x: &BigFloat,
    kind: AiryKind,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if x.is_nan() || x.is_inf() {
        return Err(unevaluable("Airy function of special float value"));
    }
    let base_wp = prec + 32;
    let x_f = bigfloat_to_f64(x, rm, cc)?;
    let ax_f = x_f.abs();
    let zeta_f = 2.0 / 3.0 * ax_f.powf(1.5);

    if 2.0 * zeta_f > (base_wp as f64) * std::f64::consts::LN_2 {
        // The phase `(2/3)|x|^{3/2}` needs its bits before the point.
        let z_bits = 3 * x.exponent().map_or(0, i64::from).max(0) / 2;
        if !zeta_f.is_finite() || z_bits > i64::try_from(cancellation_cap(prec)).unwrap_or(i64::MAX)
        {
            return Err(special_exhausted(prec));
        }
        return Ok(round_to(
            airy_asymptotic(x, kind, base_wp, rm, cc),
            prec,
            rm,
        ));
    }

    let wp = base_wp + (2.0 * zeta_f * std::f64::consts::LOG2_E).ceil() as usize + 16;
    let mut xw = x.clone();
    let _ = xw.set_precision(wp, rm);
    let one = BigFloat::from_i32(1, wp);
    let three = BigFloat::from_i32(3, wp);
    let third = one.div(&three, wp, rm);
    let two_thirds = third.mul(&BigFloat::from_i32(2, wp), wp, rm);
    let g13 = arb_gamma_real(&third, wp, rm, cc)?;
    let g23 = arb_gamma_real(&two_thirds, wp, rm, cc)?;
    let c1 = one.div(
        &bf_pow(&three, &two_thirds, wp, rm, cc).mul(&g23, wp, rm),
        wp,
        rm,
    );
    let c2 = one.div(
        &bf_pow(&three, &third, wp, rm, cc).mul(&g13, wp, rm),
        wp,
        rm,
    );

    // Series with term recurrences; the derivatives use
    // f'_k = 3k f_k / x, g'_k = (3k+1) g_k / x (k = 0 handled directly).
    let x3 = xw.mul(&xw, wp, rm).mul(&xw, wp, rm);
    let derivative = matches!(kind, AiryKind::AiPrime | AiryKind::BiPrime);
    let (mut f_sum, mut g_sum) = if derivative {
        (BigFloat::new(wp), one.clone()) // f'(0) = 0, g'(0) = 1
    } else {
        (one.clone(), xw.clone()) // f(0) = 1, g_0 = x
    };
    let mut fk = one.clone(); // x^{3k}/∏(3j−1)(3j)
    let mut gk = xw.clone(); // x^{3k+1}/∏(3j)(3j+1)
    // At x = 0 the k = 0 terms above are the exact values (every later
    // term vanishes, and the derivative recurrences would divide by x).
    let max_terms = if xw.is_zero() {
        0
    } else {
        (ax_f * 2.0) as usize + wp + 40
    };
    for k in 1..=max_terms {
        let k3 = 3 * k as i128;
        fk = fk
            .mul(&x3, wp, rm)
            .div(&BigFloat::from_i128((k3 - 1) * k3, wp), wp, rm);
        gk = gk
            .mul(&x3, wp, rm)
            .div(&BigFloat::from_i128(k3 * (k3 + 1), wp), wp, rm);
        let (tf, tg) = if derivative {
            // 3k x^{3k−1}/∏ = (3k/x) f_k ;  (3k+1) x^{3k}/∏ = ((3k+1)/x) g_k
            (
                fk.mul(&BigFloat::from_i128(k3, wp), wp, rm)
                    .div(&xw, wp, rm),
                gk.mul(&BigFloat::from_i128(k3 + 1, wp), wp, rm)
                    .div(&xw, wp, rm),
            )
        } else {
            (fk.clone(), gk.clone())
        };
        f_sum = f_sum.add(&tf, wp, rm);
        g_sum = g_sum.add(&tg, wp, rm);
        if negligible(&tf, &one, wp + 4) && negligible(&tg, &one, wp + 4) {
            break;
        }
    }
    let a = c1.mul(&f_sum, wp, rm);
    let b = c2.mul(&g_sum, wp, rm);
    let r = match kind {
        AiryKind::Ai | AiryKind::AiPrime => a.sub(&b, wp, rm),
        AiryKind::Bi | AiryKind::BiPrime => three.sqrt(wp, rm).mul(&a.add(&b, wp, rm), wp, rm),
    };
    Ok(round_to(r, prec, rm))
}

/// Asymptotic expansions of the Airy functions for large `|x|`
/// (see [`arb_airy`]).  Returns the value at working precision `wp`.
fn airy_asymptotic(
    x: &BigFloat,
    kind: AiryKind,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> BigFloat {
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let ax = x.abs();
    let sqrt_ax = ax.sqrt(wp, rm);
    let x_quarter = sqrt_ax.sqrt(wp, rm); // |x|^{1/4}
    // `ζ = (2/3)|x|^{3/2}` enters `e^{±ζ}` and the phase `ζ + π/4` through
    // its absolute error: it is formed with the `Z` bits it has before the
    // point as guard (the caller refuses beyond `cancellation_cap`).
    // Before 0.30 it was formed at `wp` bits: `airyai(−467·10⁴⁰)` was wrong
    // from its 13th digit at 30, `airyai(−29/16·10⁷⁰)` entirely.
    let wz =
        wp + usize::try_from(3 * ax.exponent().map_or(0, i64::from).max(0) / 2 + 8).unwrap_or(0);
    let ax_z = at_precision(&ax, wz, rm);
    let zeta = two.mul(&ax_z, wz, rm).mul(&ax_z.sqrt(wz, rm), wz, rm).div(
        &BigFloat::from_i32(3, wz),
        wz,
        rm,
    );
    let inv_zeta = one.div(&zeta, wp, rm);
    let sqrt_pi = cc.pi(wp, rm).clone().sqrt(wp, rm);
    let derivative = matches!(kind, AiryKind::AiPrime | AiryKind::BiPrime);

    // Coefficients c_k = u_k (or v_k) / ζ^k, u_k = u_{k−1}(6k−5)(6k−3)(6k−1)/(216 k (2k−1)),
    // v_k = −(6k+1)/(6k−1) u_k.  Optimal truncation: stop when |c_k| grows.
    let mut coeffs: Vec<BigFloat> = Vec::new();
    let mut u = one.clone();
    let mut zeta_pow = one.clone();
    let mut prev: Option<BigFloat> = None;
    for k in 0..(wp * 2 + 100) {
        if k > 0 {
            let k_i = k as i128;
            let num = BigFloat::from_i128((6 * k_i - 5) * (6 * k_i - 3) * (6 * k_i - 1), wp);
            let den = BigFloat::from_i128(216 * k_i * (2 * k_i - 1), wp);
            u = u.mul(&num, wp, rm).div(&den, wp, rm);
            zeta_pow = zeta_pow.mul(&inv_zeta, wp, rm);
        }
        let mut c = u.mul(&zeta_pow, wp, rm);
        if derivative {
            let k_i = k as i128;
            let ratio = BigFloat::from_i128(6 * k_i + 1, wp).div(
                &BigFloat::from_i128(6 * k_i - 1, wp),
                wp,
                rm,
            );
            c = c.mul(&ratio, wp, rm).neg();
        }
        if let Some(ref p) = prev
            && bf_gt(&c.abs(), p)
        {
            break;
        }
        let done = negligible(&c, &one, wp);
        prev = Some(c.abs());
        coeffs.push(c);
        if done {
            break;
        }
    }

    if !x.is_negative() {
        // Ai ~ e^{−ζ}/(2√π x^{1/4}) Σ (−1)^k u_k/ζ^k,   Bi ~ e^{ζ}/(√π x^{1/4}) Σ u_k/ζ^k
        // Ai' ~ −x^{1/4} e^{−ζ}/(2√π) Σ (−1)^k v_k/ζ^k, Bi' ~ x^{1/4} e^{ζ}/√π Σ v_k/ζ^k
        let mut sum = BigFloat::new(wp);
        let alternate = matches!(kind, AiryKind::Ai | AiryKind::AiPrime);
        for (k, c) in coeffs.iter().enumerate() {
            if alternate && k % 2 == 1 {
                sum = sum.sub(c, wp, rm);
            } else {
                sum = sum.add(c, wp, rm);
            }
        }
        let amp = match kind {
            AiryKind::Ai => zeta.neg().exp(wp, rm, cc).div(
                &two.mul(&sqrt_pi, wp, rm).mul(&x_quarter, wp, rm),
                wp,
                rm,
            ),
            AiryKind::Bi => zeta
                .exp(wp, rm, cc)
                .div(&sqrt_pi.mul(&x_quarter, wp, rm), wp, rm),
            AiryKind::AiPrime => x_quarter
                .mul(&zeta.neg().exp(wp, rm, cc), wp, rm)
                .div(&two.mul(&sqrt_pi, wp, rm), wp, rm)
                .neg(),
            AiryKind::BiPrime => x_quarter
                .mul(&zeta.exp(wp, rm, cc), wp, rm)
                .div(&sqrt_pi, wp, rm),
        };
        return amp.mul(&sum, wp, rm);
    }

    // x < 0: with θ = ζ + π/4, P = Σ (−1)^k c_{2k}, Q = Σ (−1)^k c_{2k+1}:
    // Ai  ~ (sinθ P − cosθ Q)/(√π x^{1/4}),  Bi  ~ (cosθ P + sinθ Q)/(√π x^{1/4})
    // Ai' ~ −x^{1/4}(cosθ P + sinθ Q)/√π,  Bi' ~  x^{1/4}(sinθ P − cosθ Q)/√π
    let mut p = BigFloat::new(wp);
    let mut q = BigFloat::new(wp);
    for (k, c) in coeffs.iter().enumerate() {
        let sign_neg = (k / 2) % 2 == 1;
        let target = if k % 2 == 0 { &mut p } else { &mut q };
        *target = if sign_neg {
            target.sub(c, wp, rm)
        } else {
            target.add(c, wp, rm)
        };
    }
    let pi = cc.pi(wz, rm).clone();
    let theta = zeta.add(&pi.div(&BigFloat::from_i32(4, wz), wz, rm), wz, rm);
    let s = theta.sin(wp, rm, cc);
    let c = theta.cos(wp, rm, cc);
    let sp_minus_cq = s.mul(&p, wp, rm).sub(&c.mul(&q, wp, rm), wp, rm);
    let cp_plus_sq = c.mul(&p, wp, rm).add(&s.mul(&q, wp, rm), wp, rm);
    match kind {
        AiryKind::Ai => sp_minus_cq.div(&sqrt_pi.mul(&x_quarter, wp, rm), wp, rm),
        AiryKind::Bi => cp_plus_sq.div(&sqrt_pi.mul(&x_quarter, wp, rm), wp, rm),
        AiryKind::AiPrime => x_quarter
            .mul(&cp_plus_sq, wp, rm)
            .div(&sqrt_pi, wp, rm)
            .neg(),
        AiryKind::BiPrime => x_quarter.mul(&sp_minus_cq, wp, rm).div(&sqrt_pi, wp, rm),
    }
}

// ── Elliptic integrals (Carlson symmetric forms) ────────────────────────────────

/// Are `a`, `b`, `c` (and `d`) equal to within `2^{−bits}` relative?
fn all_close(vals: &[&BigFloat], bits: usize, wp: usize, rm: RoundingMode) -> bool {
    let first = vals[0];
    vals[1..]
        .iter()
        .all(|v| negligible(&v.sub(first, wp, rm), first, bits))
}

/// Convergence threshold for the Carlson duplication iterations: the
/// remainder of `R_F`, `R_D`, `R_J` at arguments within relative spread `δ`
/// of their mean is `O(δ²)` (the Taylor expansions have no linear term), so
/// a spread of `2^{−wp/2}` already gives `wp` correct bits — and stopping
/// there avoids stalling on rounding noise in the last bits.
fn carlson_bits(wp: usize) -> usize {
    wp / 2 + 8
}

/// Carlson `R_C(x, y) = R_F(x, y, y)`, `x ≥ 0`, `y > 0`.
///
/// With `w = (y − x)/y`, `R_C = y^{−1/2} arcsin(√w)/√w = y^{−1/2} Σ_k C(2k,k) w^k / (4^k (2k+1))`
/// (the series is analytic through `w = 0`, covering `x > y` as well).
/// The series is used for `|w| < 1/10`: the closed forms
/// `arccos(√(x/y))/√(y−x)` / `arccosh(√(x/y))/√(x−y)` lose relative
/// precision like `1/w` there, which the `R_J` duplication (where
/// `y − x` shrinks quadratically) would amplify into a first-order error.
fn carlson_rc(
    x: &BigFloat,
    y: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> BigFloat {
    let one = BigFloat::from_i32(1, wp);
    let diff = y.sub(x, wp, rm);
    let inv_sqrt_y = one.div(&y.sqrt(wp, rm), wp, rm);
    if diff.is_zero() {
        return inv_sqrt_y;
    }
    let w = diff.div(y, wp, rm);
    let w_f = bigfloat_to_f64(&w, rm, cc).unwrap_or(1.0);
    if w_f.abs() < 0.1 {
        // c_k = c_{k−1} (2k−1)² / ((2k)(2k+1)):  1, 1/6, 3/40, 5/112, …
        let mut sum = one.clone();
        let mut c = one.clone();
        let mut wk = one.clone();
        for k in 1..(wp * 2 + 100) {
            let k_i = k as i128;
            let num = BigFloat::from_i128((2 * k_i - 1) * (2 * k_i - 1), wp);
            let den = BigFloat::from_i128(2 * k_i * (2 * k_i + 1), wp);
            c = c.mul(&num, wp, rm).div(&den, wp, rm);
            wk = wk.mul(&w, wp, rm);
            let term = c.mul(&wk, wp, rm);
            sum = sum.add(&term, wp, rm);
            if negligible(&term, &sum, wp) {
                break;
            }
        }
        return inv_sqrt_y.mul(&sum, wp, rm);
    }
    let ratio = x.div(y, wp, rm).sqrt(wp, rm); // √(x/y)
    if diff.is_positive() {
        // y > x: arccos(√(x/y)) / √(y − x)
        ratio.acos(wp, rm, cc).div(&diff.sqrt(wp, rm), wp, rm)
    } else {
        // x > y: arccosh(√(x/y)) / √(x − y)
        ratio
            .acosh(wp, rm, cc)
            .div(&diff.neg().sqrt(wp, rm), wp, rm)
    }
}

/// Carlson `R_F(x, y, z)` (`x, y, z ≥ 0`, at most one zero) by the
/// duplication theorem iterated until the arguments coincide to working
/// precision, where `R_F(μ, μ, μ) = μ^{−1/2}`.
fn carlson_rf(
    x: &BigFloat,
    y: &BigFloat,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
) -> Result<BigFloat, SymplexError> {
    let four = BigFloat::from_i32(4, wp);
    let (mut x, mut y, mut z) = (x.clone(), y.clone(), z.clone());
    for _ in 0..(wp * 2 + 200) {
        if all_close(&[&x, &y, &z], carlson_bits(wp), wp, rm) {
            // R_F(μ, μ, μ) = μ^{−1/2}, μ = (x + y + z)/3
            let one = BigFloat::from_i32(1, wp);
            let mu = x
                .add(&y, wp, rm)
                .add(&z, wp, rm)
                .div(&BigFloat::from_i32(3, wp), wp, rm);
            return Ok(one.div(&mu.sqrt(wp, rm), wp, rm));
        }
        let (sx, sy, sz) = (x.sqrt(wp, rm), y.sqrt(wp, rm), z.sqrt(wp, rm));
        let lambda =
            sx.mul(&sy, wp, rm)
                .add(&sy.mul(&sz, wp, rm), wp, rm)
                .add(&sz.mul(&sx, wp, rm), wp, rm);
        x = x.add(&lambda, wp, rm).div(&four, wp, rm);
        y = y.add(&lambda, wp, rm).div(&four, wp, rm);
        z = z.add(&lambda, wp, rm).div(&four, wp, rm);
    }
    Err(SymplexError::ComputationFailed {
        operation: "evalf",
        reason: "Carlson R_F did not converge".into(),
    })
}

/// Carlson `R_D(x, y, z) = R_J(x, y, z, z)` (`z > 0`) by duplication:
/// `R_D(x,y,z) = R_D(x',y',z')/4 + 3/(√z (z + λ))`, `R_D(μ,μ,μ) = μ^{−3/2}`.
fn carlson_rd(
    x: &BigFloat,
    y: &BigFloat,
    z: &BigFloat,
    wp: usize,
    rm: RoundingMode,
) -> Result<BigFloat, SymplexError> {
    let one = BigFloat::from_i32(1, wp);
    let three = BigFloat::from_i32(3, wp);
    let four = BigFloat::from_i32(4, wp);
    let (mut x, mut y, mut z) = (x.clone(), y.clone(), z.clone());
    let mut acc = BigFloat::new(wp);
    let mut scale = one.clone(); // 4^{−k}
    for _ in 0..(wp * 2 + 200) {
        if all_close(&[&x, &y, &z], carlson_bits(wp), wp, rm) {
            // R_D(μ, μ, μ) = μ^{−3/2}, μ = (x + y + 3z)/5
            let mu = x.add(&y, wp, rm).add(&three.mul(&z, wp, rm), wp, rm).div(
                &BigFloat::from_i32(5, wp),
                wp,
                rm,
            );
            let tail = one.div(&mu.mul(&mu.sqrt(wp, rm), wp, rm), wp, rm);
            return Ok(acc.add(&scale.mul(&tail, wp, rm), wp, rm));
        }
        let (sx, sy, sz) = (x.sqrt(wp, rm), y.sqrt(wp, rm), z.sqrt(wp, rm));
        let lambda =
            sx.mul(&sy, wp, rm)
                .add(&sy.mul(&sz, wp, rm), wp, rm)
                .add(&sz.mul(&sx, wp, rm), wp, rm);
        let term = three.div(&sz.mul(&z.add(&lambda, wp, rm), wp, rm), wp, rm);
        acc = acc.add(&scale.mul(&term, wp, rm), wp, rm);
        scale = scale.div(&four, wp, rm);
        x = x.add(&lambda, wp, rm).div(&four, wp, rm);
        y = y.add(&lambda, wp, rm).div(&four, wp, rm);
        z = z.add(&lambda, wp, rm).div(&four, wp, rm);
    }
    Err(SymplexError::ComputationFailed {
        operation: "evalf",
        reason: "Carlson R_D did not converge".into(),
    })
}

/// Carlson `R_J(x, y, z, p)` for `p > 0` by duplication:
/// `R_J = R_J(x',y',z',p')/4 + 3 R_C(α², β²)` with
/// `α = p(√x + √y + √z) + √x√y√z`, `β = √p (p + λ)`, `R_J(μ,μ,μ,μ) = μ^{−3/2}`.
fn carlson_rj(
    x: &BigFloat,
    y: &BigFloat,
    z: &BigFloat,
    p: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if !p.is_positive() {
        return Err(unevaluable(
            "elliptic_pi: the characteristic n must satisfy n < 1 for a real value",
        ));
    }
    let one = BigFloat::from_i32(1, wp);
    let three = BigFloat::from_i32(3, wp);
    let four = BigFloat::from_i32(4, wp);
    let (mut x, mut y, mut z, mut p) = (x.clone(), y.clone(), z.clone(), p.clone());
    let mut acc = BigFloat::new(wp);
    let mut scale = one.clone();
    for _ in 0..(wp * 2 + 200) {
        if all_close(&[&x, &y, &z, &p], carlson_bits(wp), wp, rm) {
            // R_J(μ, μ, μ, μ) = μ^{−3/2}, μ = (x + y + z + 2p)/5
            let two_p = p.mul(&BigFloat::from_i32(2, wp), wp, rm);
            let mu = x.add(&y, wp, rm).add(&z, wp, rm).add(&two_p, wp, rm).div(
                &BigFloat::from_i32(5, wp),
                wp,
                rm,
            );
            let tail = one.div(&mu.mul(&mu.sqrt(wp, rm), wp, rm), wp, rm);
            return Ok(acc.add(&scale.mul(&tail, wp, rm), wp, rm));
        }
        let (sx, sy, sz, sp) = (
            x.sqrt(wp, rm),
            y.sqrt(wp, rm),
            z.sqrt(wp, rm),
            p.sqrt(wp, rm),
        );
        let lambda =
            sx.mul(&sy, wp, rm)
                .add(&sy.mul(&sz, wp, rm), wp, rm)
                .add(&sz.mul(&sx, wp, rm), wp, rm);
        let alpha = p.mul(&sx.add(&sy, wp, rm).add(&sz, wp, rm), wp, rm).add(
            &sx.mul(&sy, wp, rm).mul(&sz, wp, rm),
            wp,
            rm,
        );
        let beta = sp.mul(&p.add(&lambda, wp, rm), wp, rm);
        let rc = carlson_rc(
            &alpha.mul(&alpha, wp, rm),
            &beta.mul(&beta, wp, rm),
            wp,
            rm,
            cc,
        );
        acc = acc.add(&scale.mul(&three.mul(&rc, wp, rm), wp, rm), wp, rm);
        scale = scale.div(&four, wp, rm);
        x = x.add(&lambda, wp, rm).div(&four, wp, rm);
        y = y.add(&lambda, wp, rm).div(&four, wp, rm);
        z = z.add(&lambda, wp, rm).div(&four, wp, rm);
        p = p.add(&lambda, wp, rm).div(&four, wp, rm);
    }
    Err(SymplexError::ComputationFailed {
        operation: "evalf",
        reason: "Carlson R_J did not converge".into(),
    })
}

/// `1 − m` with a domain check (`m < 1` required for a real `K`, `E`, `Π`).
fn one_minus_m(
    m: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    what: &str,
) -> Result<BigFloat, SymplexError> {
    let one = BigFloat::from_i32(1, wp);
    let v = one.sub(m, wp, rm);
    if v.is_negative() {
        return Err(unevaluable(format!(
            "{what}: parameter m must satisfy m ≤ 1 for a real value"
        )));
    }
    Ok(v)
}

/// Complete elliptic integral of the first kind `K(m) = R_F(0, 1−m, 1)`.
fn arb_elliptic_k(
    m: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if m.is_nan() || m.is_inf() {
        return Err(unevaluable("elliptic_k of special float value"));
    }
    let wp = prec + 32;
    let y = one_minus_m(m, wp, rm, "elliptic_k")?;
    if y.is_zero() {
        return Err(unevaluable("elliptic_k(1) is infinite"));
    }
    let _ = cc;
    let r = carlson_rf(&BigFloat::new(wp), &y, &BigFloat::from_i32(1, wp), wp, rm)?;
    Ok(round_to(r, prec, rm))
}

/// Complete elliptic integral of the second kind
/// `E(m) = R_F(0, 1−m, 1) − (m/3) R_D(0, 1−m, 1)`.
fn arb_elliptic_e(
    m: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if m.is_nan() || m.is_inf() {
        return Err(unevaluable("elliptic_e of special float value"));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let y = one_minus_m(m, wp, rm, "elliptic_e")?;
    if y.is_zero() {
        return Ok(BigFloat::from_i32(1, prec));
    }
    let _ = cc;
    let zero = BigFloat::new(wp);
    let rf = carlson_rf(&zero, &y, &one, wp, rm)?;
    let rd = carlson_rd(&zero, &y, &one, wp, rm)?;
    let three = BigFloat::from_i32(3, wp);
    let r = rf.sub(&m.mul(&rd, wp, rm).div(&three, wp, rm), wp, rm);
    Ok(round_to(r, prec, rm))
}

/// Incomplete elliptic integral of the first kind
/// `F(φ | m) = sinφ · R_F(cos²φ, 1 − m sin²φ, 1)` for `|φ| ≤ π/2`, extended
/// by `F(φ + kπ | m) = F(φ | m) + 2k K(m)`.
fn arb_elliptic_f(
    phi: &BigFloat,
    m: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if phi.is_nan() || phi.is_inf() || m.is_nan() || m.is_inf() {
        return Err(unevaluable("elliptic_f of special float value"));
    }
    if phi.is_zero() {
        return Ok(BigFloat::new(prec));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let pi = cc.pi(wp, rm).clone();
    // Reduce φ to [−π/2, π/2]: φ = φ₀ + kπ.
    let k_bf = phi
        .div(&pi, wp, rm)
        .add(&BigFloat::from_f64(0.5, wp), wp, rm)
        .floor();
    let phi0 = phi.sub(&k_bf.mul(&pi, wp, rm), wp, rm);
    let s = phi0.sin(wp, rm, cc);
    let c = phi0.cos(wp, rm, cc);
    let s2 = s.mul(&s, wp, rm);
    let c2 = c.mul(&c, wp, rm);
    let y = one.sub(&m.mul(&s2, wp, rm), wp, rm);
    if !y.is_positive() {
        return Err(unevaluable(
            "elliptic_f: 1 − m sin²φ must be positive for a real value",
        ));
    }
    let mut r = s.mul(&carlson_rf(&c2, &y, &one, wp, rm)?, wp, rm);
    if !k_bf.is_zero() {
        let k = arb_elliptic_k(m, wp, rm, cc)?;
        let two = BigFloat::from_i32(2, wp);
        r = r.add(&two.mul(&k_bf, wp, rm).mul(&k, wp, rm), wp, rm);
    }
    Ok(round_to(r, prec, rm))
}

/// Complete elliptic integral of the third kind
/// `Π(n | m) = R_F(0, 1−m, 1) + (n/3) R_J(0, 1−m, 1, 1−n)` for `n < 1`, `m < 1`.
fn arb_elliptic_pi(
    n: &BigFloat,
    m: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    if n.is_nan() || n.is_inf() || m.is_nan() || m.is_inf() {
        return Err(unevaluable("elliptic_pi of special float value"));
    }
    let wp = prec + 32;
    let one = BigFloat::from_i32(1, wp);
    let zero = BigFloat::new(wp);
    let y = one_minus_m(m, wp, rm, "elliptic_pi")?;
    if y.is_zero() {
        return Err(unevaluable("elliptic_pi(n, 1) is infinite"));
    }
    let p = one.sub(n, wp, rm);
    let rf = carlson_rf(&zero, &y, &one, wp, rm)?;
    if n.is_zero() {
        return Ok(round_to(rf, prec, rm));
    }
    let rj = carlson_rj(&zero, &y, &one, &p, wp, rm, cc)?;
    let three = BigFloat::from_i32(3, wp);
    let r = rf.add(&n.mul(&rj, wp, rm).div(&three, wp, rm), wp, rm);
    Ok(round_to(r, prec, rm))
}

// ── Orthogonal polynomials with parameters ───────────────────────────────────────

/// The degree of an orthogonal polynomial as a non-negative integer.
fn poly_degree(
    n: &BigFloat,
    what: &str,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<u64, SymplexError> {
    // An integer exactly: before 0.29 a degree within 10⁻¹² of one was
    // taken for it (`jacobi(3 + 10⁻¹³, …)` evaluated the cubic).
    match bf_as_int(n, rm, cc)? {
        Some(d) if n.is_int() && (0..=10_000_000).contains(&d) => Ok(d as u64),
        _ => Err(unevaluable(format!(
            "{what}: degree must be a non-negative integer"
        ))),
    }
}

/// Gegenbauer `C_n^{(a)}(x)`: `(k+1) C_{k+1} = 2(k+a) x C_k − (k+2a−1) C_{k−1}`.
fn arb_gegenbauer(
    n: &BigFloat,
    a: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let deg = poly_degree(n, "gegenbauer", rm, cc)?;
    let wp = prec + 32 + (deg as f64).log2().ceil().max(0.0) as usize;
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    if deg == 0 {
        return Ok(BigFloat::from_i32(1, prec));
    }
    let mut prev = one.clone();
    let mut curr = two.mul(a, wp, rm).mul(x, wp, rm);
    for k in 1..deg {
        let k_bf = BigFloat::from_i128(k as i128, wp);
        let t1 = two
            .mul(&k_bf.add(a, wp, rm), wp, rm)
            .mul(x, wp, rm)
            .mul(&curr, wp, rm);
        let coeff = k_bf.add(&two.mul(a, wp, rm), wp, rm).sub(&one, wp, rm);
        let t2 = coeff.mul(&prev, wp, rm);
        let next = t1
            .sub(&t2, wp, rm)
            .div(&BigFloat::from_i128(k as i128 + 1, wp), wp, rm);
        prev = curr;
        curr = next;
    }
    Ok(round_to(curr, prec, rm))
}

/// The largest degree of [`arb_jacobi`]: its sum takes `O(n)` operations at
/// about `n·log₂(1 + √(1 − x²))` bits: 0.12 s at 2500, 0.6 s at 5000
/// (release), and `O(n²)` with the precision beyond.
const MAX_JACOBI_DEGREE: usize = 5000;

/// Jacobi `P_n^{(a,b)}(x)` via the explicit sum
/// `Σ_s C(n+a, n−s) C(n+b, s) ((x−1)/2)^s ((x+1)/2)^{n−s}`, its
/// cancellation measured: the largest term over the value, made up with as
/// many more bits (mpmath's `hypsum` does the same for the `₂F₁` of its
/// `jacobi`).  The first pass takes `2n` guard bits up to degree 2000 (the
/// same digits as before 0.35, which took them unmeasured — a value next to
/// a zero of `P_n` could lose more), `n·log₂(1 + √(1 − x²))` beyond (the
/// terms' sum over the value's scale for `abs(x) < 1`).  Before 0.35 a degree
/// beyond 2000 was refused: `jacobi(2500, 1/3, 1/5, 1/7)`.
///
/// The coefficients are updated term by term: `∏_{j>s}(a + j)` divided by
/// `a + s` (from the first `s` at which it is nonzero: a negative integer
/// `a = −m` makes the terms below `m` zero), `∏_{j>n−s}(b + j)` multiplied by
/// `b + n − s + 1`, `1/((n−s)!·s!)` by `(n − s + 1)/s`, the powers by
/// `(x−1)/2` and divided by `(x+1)/2`.  Before 0.34 each term recomputed its
/// products and factorials (`O(n²)` operations and exact factorials):
/// `jacobi(1000, 1/3, 1/5, 1/3)` 1.3 s, `jacobi(2000, …)` and up never
/// finished.  Refused beyond [`MAX_JACOBI_DEGREE`].
fn arb_jacobi(
    n: &BigFloat,
    a: &BigFloat,
    b: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let deg = poly_degree(n, "jacobi", rm, cc)? as usize;
    if deg > MAX_JACOBI_DEGREE {
        return Err(SymplexError::NotImplemented(format!(
            "jacobi of degree {deg} (at most {MAX_JACOBI_DEGREE} in evalf)"
        )));
    }
    if deg == 0 {
        return Ok(BigFloat::from_i32(1, prec));
    }
    // `P_n^(a,b)(−x) = (−1)ⁿ P_n^(b,a)(x)`: 0 at `x = 0` for `a = b` and an
    // odd `n` (whose terms cancel exactly, which no measure of the loss
    // certifies).
    if x.is_zero() && deg % 2 == 1 && a.cmp(b) == Some(0) {
        return Ok(BigFloat::new(prec));
    }
    // The rounding of the sum: each term carries at most `12(n + 2)` roundings
    // relative (running products, powers), the additions `n` of the largest
    // partial sum: below `2^(4 + 2·log₂(n + 2) − wp)` of the largest term.
    let rounding = 4 + 2 * (usize::BITS - (deg + 2).leading_zeros()) as usize;
    // The first pass: `2n` guard bits up to the old maximum (the same digits
    // as before 0.35), beyond the cancellation of `abs(x) < 1` estimated as
    // `n·log₂(1 + √(1 − x²))` (the terms' sum over the value's scale).
    let first_extra = if deg <= 2000 {
        32 + 2 * deg
    } else {
        let xf = bigfloat_to_f64_rounded(x, rm)?.abs();
        let est = if xf < 1.0 {
            deg as f64 * (1.0 + (1.0 - xf * xf).sqrt()).log2()
        } else {
            0.0
        };
        40 + rounding + est.ceil() as usize
    };
    // At most the `2n` guard bits of before 0.35 beyond `cancellation_cap`.
    let cap = cancellation_cap(prec) + 2 * deg + 64;
    let mut extra = first_extra;
    loop {
        let wp = prec + extra;
        let (sum, largest) = jacobi_sum(deg, a, b, x, wp, rm, cc)?;
        // The loss: the largest term over the value.
        let lost = match (sum.exponent(), largest) {
            (Some(e), Some(l)) if !sum.is_zero() => (i64::from(l) - i64::from(e)).max(0) as usize,
            (_, None) => 0,
            _ => wp,
        };
        if lost + rounding + 8 <= extra {
            return Ok(round_to(sum, prec, rm));
        }
        if extra >= cap {
            return Err(special_exhausted(prec));
        }
        extra = (lost + rounding + 40).max(extra + 64).min(cap);
    }
}

/// The sum of [`arb_jacobi`] at `wp` bits, and the exponent of its largest
/// term (`None` when all are 0).
fn jacobi_sum(
    deg: usize,
    a: &BigFloat,
    b: &BigFloat,
    x: &BigFloat,
    wp: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<(BigFloat, Option<i32>), SymplexError> {
    let one = BigFloat::from_i32(1, wp);
    let two = BigFloat::from_i32(2, wp);
    let lo = x.sub(&one, wp, rm).div(&two, wp, rm);
    let hi = x.add(&one, wp, rm).div(&two, wp, rm);
    let int = |j: usize| BigFloat::from_u64(j as u64, 64);
    // ∏_{j=from}^{deg} (p + j).
    let shifted = |p: &BigFloat, from: usize| -> BigFloat {
        let mut acc = one.clone();
        for j in from..=deg {
            acc = acc.mul(&p.add(&int(j), wp, rm), wp, rm);
        }
        acc
    };
    // `a + j` vanishes at `j = −a` for a negative integer `a`: the terms
    // `s < −a` (whose product holds that factor) are 0.
    let first = match bf_as_int(a, rm, cc)? {
        Some(m) if a.is_int() && m < 0 && m.unsigned_abs() as usize <= deg => {
            m.unsigned_abs() as usize
        }
        _ => 0,
    };
    // The sum over `s ≥ first`: (x+1)/2 = 0 leaves the term `s = n` alone.
    let hi_zero = hi.is_zero();
    let ratio = if hi_zero {
        BigFloat::new(wp)
    } else {
        lo.div(&hi, wp, rm)
    };
    let mut pa = shifted(a, first + 1);
    let mut pb = one.clone();
    for s in 1..=first {
        pb = pb.mul(&b.add(&int(deg - s + 1), wp, rm), wp, rm);
    }
    // 1/((n − first)!·first!).
    let f0 = factorial_bigint(deg - first) * factorial_bigint(first);
    let mut inv_fact = one.div(&ratio_to_bigfloat(&f0, wp, rm), wp, rm);
    // lo^first·hi^(n − first).
    let direct_pow = |s: usize| lo.powi(s, wp, rm).mul(&hi.powi(deg - s, wp, rm), wp, rm);
    let mut pow = if hi_zero {
        BigFloat::new(wp)
    } else {
        direct_pow(first)
    };
    // A first power beyond the exponent range (`x` within `2^(−wp/n)`-ish of
    // −1): every power directly, as before 0.34.
    let direct = !hi_zero && !lo.is_zero() && (pow.is_zero() || pow.is_inf());
    let mut sum = BigFloat::new(wp);
    let mut largest: Option<i32> = None;
    for s in first..=deg {
        if s > first {
            pa = pa.div(&a.add(&int(s), wp, rm), wp, rm);
            pb = pb.mul(&b.add(&int(deg - s + 1), wp, rm), wp, rm);
            inv_fact = inv_fact.mul(&int(deg - s + 1), wp, rm).div(&int(s), wp, rm);
            pow = if direct {
                direct_pow(s)
            } else {
                pow.mul(&ratio, wp, rm)
            };
        }
        if hi_zero && s == deg {
            pow = lo.powi(deg, wp, rm);
        }
        let term = pa.mul(&pb, wp, rm).mul(&inv_fact, wp, rm).mul(&pow, wp, rm);
        if let Some(e) = term.exponent().filter(|_| !term.is_zero()) {
            largest = Some(largest.map_or(e, |l| l.max(e)));
        }
        sum = sum.add(&term, wp, rm);
    }
    Ok((sum, largest))
}

/// `n!` as a rational.
fn factorial_bigint(n: usize) -> Ratio<BigInt> {
    let mut f = BigInt::from(1);
    for i in 2..=n {
        f *= BigInt::from(i as u64);
    }
    Ratio::from_integer(f)
}

/// Associated Legendre `P_n^m(x)` (Condon–Shortley phase) for integer
/// `n ≥ 0`, integer `m`, real `x` (`|x| ≤ 1` when `m` is odd).
fn arb_assoc_legendre(
    n: &BigFloat,
    m: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let deg = poly_degree(n, "assoc_legendre", rm, cc)? as i64;
    let order = bf_as_int(m, rm, cc)?
        .filter(|_| m.is_int())
        .ok_or_else(|| unevaluable("assoc_legendre: order must be an integer"))?;
    if order.abs() > deg {
        return Ok(BigFloat::new(prec));
    }
    let wp = prec + 32 + 2 * (deg as f64).log2().ceil().max(0.0) as usize;
    let one = BigFloat::from_i32(1, wp);
    let mu = order.unsigned_abs() as usize;
    let x2 = x.mul(x, wp, rm);
    let one_minus_x2 = one.sub(&x2, wp, rm);
    // (1 − x²)^{μ/2}
    let root_pow = if mu.is_multiple_of(2) {
        one_minus_x2.powi(mu / 2, wp, rm)
    } else {
        if one_minus_x2.is_negative() {
            return Err(unevaluable(
                "assoc_legendre with odd order is complex for |x| > 1",
            ));
        }
        one_minus_x2
            .sqrt(wp, rm)
            .mul(&one_minus_x2.powi(mu / 2, wp, rm), wp, rm)
    };
    // P_μ^μ = (−1)^μ (2μ−1)!! (1−x²)^{μ/2}
    let mut dfact = BigInt::from(1);
    for j in 1..=mu {
        dfact *= BigInt::from((2 * j - 1) as u64);
    }
    if mu % 2 == 1 {
        dfact = -dfact;
    }
    let mut prev = ratio_to_bigfloat(&Ratio::from_integer(dfact), wp, rm).mul(&root_pow, wp, rm);
    let deg_u = deg as usize;
    let mut curr = if deg_u > mu {
        BigFloat::from_i128(2 * mu as i128 + 1, wp)
            .mul(x, wp, rm)
            .mul(&prev, wp, rm)
    } else {
        prev.clone()
    };
    for k in (mu + 1)..deg_u {
        let t1 = BigFloat::from_i128(2 * k as i128 + 1, wp)
            .mul(x, wp, rm)
            .mul(&curr, wp, rm);
        let t2 = BigFloat::from_i128((k + mu) as i128, wp).mul(&prev, wp, rm);
        let next = t1
            .sub(&t2, wp, rm)
            .div(&BigFloat::from_i128((k - mu + 1) as i128, wp), wp, rm);
        prev = curr;
        curr = next;
    }
    if order < 0 {
        // P_n^{−μ} = (−1)^μ (n−μ)!/(n+μ)! P_n^μ
        let mut ratio = factorial_bigint(deg_u - mu) / factorial_bigint(deg_u + mu);
        if mu % 2 == 1 {
            ratio = -ratio;
        }
        curr = curr.mul(&ratio_to_bigfloat(&ratio, wp, rm), wp, rm);
    }
    Ok(round_to(curr, prec, rm))
}

/// Generalised Laguerre `L_n^{(a)}(x)`:
/// `(k+1) L_{k+1} = (2k+1+a−x) L_k − (k+a) L_{k−1}`.
fn arb_assoc_laguerre(
    n: &BigFloat,
    a: &BigFloat,
    x: &BigFloat,
    prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<BigFloat, SymplexError> {
    let deg = poly_degree(n, "assoc_laguerre", rm, cc)?;
    let wp = prec + 32 + (deg as f64).log2().ceil().max(0.0) as usize;
    let one = BigFloat::from_i32(1, wp);
    if deg == 0 {
        return Ok(BigFloat::from_i32(1, prec));
    }
    let mut prev = one.clone();
    let mut curr = one.add(a, wp, rm).sub(x, wp, rm);
    for k in 1..deg {
        let k_bf = BigFloat::from_i128(k as i128, wp);
        let coeff = BigFloat::from_i128(2 * k as i128 + 1, wp)
            .add(a, wp, rm)
            .sub(x, wp, rm);
        let t1 = coeff.mul(&curr, wp, rm);
        let t2 = k_bf.add(a, wp, rm).mul(&prev, wp, rm);
        let next = t1
            .sub(&t2, wp, rm)
            .div(&BigFloat::from_i128(k as i128 + 1, wp), wp, rm);
        prev = curr;
        curr = next;
    }
    Ok(round_to(curr, prec, rm))
}

/// The reason of the error [`get_cached`] raises for a sub-expression
/// with no value ([`root_cause`] replaces it by the sub-expression's own
/// error).
fn not_evaluated_reason(id: ExprId) -> String {
    format!("sub-expression {id:?} has no numerical value")
}

fn get_cached(cache: &FxHashMap<ExprId, Complex>, id: ExprId) -> Result<&Complex, SymplexError> {
    cache.get(&id).ok_or_else(|| SymplexError::Unevaluable {
        reason: not_evaluated_reason(id),
    })
}

/// Convert a `Ratio<BigInt>` to a `BigFloat` with the given precision in
/// bits (see [`crate::base::numeric::ratio_to_bigfloat`]).
fn ratio_to_bigfloat(r: &Ratio<BigInt>, prec: usize, rm: RoundingMode) -> BigFloat {
    crate::base::numeric::ratio_to_bigfloat(r, prec, rm)
}

/// Try to extract a small integer exponent (fits in i32) from an ExprId.
fn try_as_small_int(arena: &Arena, id: ExprId) -> Option<i32> {
    let r = arena.as_num(id)?;
    if !r.is_integer() {
        return None;
    }
    let n = r.to_integer();
    let val: i64 = n.try_into().ok()?;
    if val >= i32::MIN as i64 && val <= i32::MAX as i64 {
        Some(val as i32)
    } else {
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Decimal / complex formatting
// ═══════════════════════════════════════════════════════════════════════════

/// Determine whether `part` is negligibly small compared to `other`.
///
/// Returns `true` if `part` is zero, or if its binary exponent is more
/// than `digits * log2(10)` bits below `other`'s exponent (meaning it
/// is below the requested output precision).
fn is_negligible_part(part: &BigFloat, other: &BigFloat, digits: u32) -> bool {
    if part.is_zero() {
        return true;
    }
    if other.is_zero() {
        return false;
    }
    match (part.exponent(), other.exponent()) {
        (Some(p_exp), Some(o_exp)) => {
            let bit_threshold = (digits as i64) * 34 / 10 + 4;
            (o_exp as i64 - p_exp as i64) > bit_threshold
        }
        _ => false,
    }
}

/// Format a complex result as a string.
///
/// If the imaginary part is negligible, formats as a real number.
/// If the real part is negligible, formats as a pure imaginary number.
/// Otherwise formats as `a + b*i` or `a - b*i`.
fn format_complex(
    z: &Complex,
    digits: u32,
    _prec: usize,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<String, SymplexError> {
    let re = &z.0;
    let im = &z.1;

    let re_negligible = is_negligible_part(re, im, digits);
    let im_negligible = is_negligible_part(im, re, digits);

    if re_negligible && im_negligible {
        return Ok("0".to_string());
    }

    if im_negligible {
        return format_decimal(re, digits, rm, cc);
    }

    if re_negligible {
        // Pure imaginary.
        let im_str = format_decimal(im, digits, rm, cc)?;
        return if im_str == "1" {
            Ok("i".to_string())
        } else if im_str == "-1" {
            Ok("-i".to_string())
        } else {
            Ok(format!("{im_str}*i"))
        };
    }

    // Both parts present.
    let re_str = format_decimal(re, digits, rm, cc)?;
    if im.is_negative() {
        let im_abs_str = format_decimal(&im.abs(), digits, rm, cc)?;
        if im_abs_str == "1" {
            Ok(format!("{re_str} - i"))
        } else {
            Ok(format!("{re_str} - {im_abs_str}*i"))
        }
    } else {
        let im_str = format_decimal(im, digits, rm, cc)?;
        if im_str == "1" {
            Ok(format!("{re_str} + i"))
        } else {
            Ok(format!("{re_str} + {im_str}*i"))
        }
    }
}

/// Round a decimal digit string `0.d1d2d3…` to `digits` significant digits.
///
/// Rounds to nearest, ties to even (the digits beyond the requested
/// count are exact decimal digits of the binary value, so an exact tie is
/// a genuine `…5000…`).  Carries propagate leftwards; a carry out of the
/// leading digit (`9.9996 → 10.00`) is reported as an exponent increment
/// so the caller can re-place the decimal point.
///
/// Returns `(rounded_digits, exponent_increment)`; when `mantissa` has no
/// more than `digits` digits it is returned unchanged.
fn round_decimal_digits(mantissa: &[u8], digits: usize) -> (Vec<u8>, i64) {
    if digits == 0 || mantissa.len() <= digits {
        return (mantissa.to_vec(), 0);
    }
    let mut kept: Vec<u8> = mantissa[..digits].to_vec();
    let next = mantissa[digits];
    let rest_nonzero = mantissa[digits + 1..].iter().any(|&d| d != 0);
    let round_up = match next.cmp(&5) {
        std::cmp::Ordering::Greater => true,
        std::cmp::Ordering::Less => false,
        // Exactly half: ties to even.
        std::cmp::Ordering::Equal => rest_nonzero || kept[digits - 1] % 2 == 1,
    };
    if !round_up {
        return (kept, 0);
    }
    // Propagate the carry from the last kept digit leftwards.
    for d in kept.iter_mut().rev() {
        if *d == 9 {
            *d = 0;
        } else {
            *d += 1;
            return (kept, 0);
        }
    }
    // Carried out of the leading digit: 0.999… → 1.000… × 10.
    kept[0] = 1;
    (kept, 1)
}

/// Format a `BigFloat` as a decimal string with `digits` significant digits.
///
/// Uses astro-float's `convert_to_radix` for reliable base-10 conversion,
/// rounds to `digits` significant digits, then formats the result with
/// proper decimal point placement.
fn format_decimal(
    val: &BigFloat,
    digits: u32,
    rm: RoundingMode,
    cc: &mut Consts,
) -> Result<String, SymplexError> {
    if val.is_zero() {
        return Ok("0".to_string());
    }

    if val.is_inf_pos() {
        return Ok("oo".to_string());
    }
    if val.is_inf_neg() {
        return Ok("-oo".to_string());
    }

    // Use the library's decimal conversion.
    let (sign, mantissa, exponent) = val
        .convert_to_radix(Radix::Dec, rm, cc)
        .map_err(|e| SymplexError::NotImplemented(format!("decimal conversion failed: {e:?}")))?;

    let sign_str = if sign == Sign::Neg { "-" } else { "" };

    // mantissa is Vec<u8> of decimal digits [d1, d2, d3, ...]
    // representing the value 0.d1d2d3... × 10^exponent.
    // So the actual value is d1.d2d3... × 10^(exponent-1).

    // Round (not truncate) to the requested digit count.
    let (rounded, exp_carry) = round_decimal_digits(&mantissa, digits as usize);
    let n = rounded.len();
    if n == 0 {
        return Ok("0".to_string());
    }

    let digit_chars: Vec<char> = rounded.iter().map(|&d| (b'0' + d) as char).collect();

    // The "adjusted exponent" is exponent-1 (shifting from 0.ddd to d.ddd notation).
    let adj_exp = exponent as i64 - 1 + exp_carry;

    // Decide between plain decimal and scientific notation.
    if adj_exp >= 0 && (adj_exp as usize) < n {
        // The decimal point falls within the digit string.
        // E.g., digits=[3,1,4,1,5], adj_exp=0 → "3.1415"
        let dot_pos = adj_exp as usize + 1;
        let mut s = String::with_capacity(n + 2);
        s.push_str(sign_str);
        for (i, &ch) in digit_chars.iter().enumerate() {
            if i == dot_pos && dot_pos < n {
                s.push('.');
            }
            s.push(ch);
        }
        // Trim trailing zeros after the decimal point.
        if s.contains('.') {
            let trimmed = s.trim_end_matches('0').trim_end_matches('.');
            Ok(trimmed.to_string())
        } else {
            Ok(s)
        }
    } else if adj_exp >= 0 && (adj_exp as usize) < n + 6 {
        // Small integer — pad with trailing zeros.
        let mut s = String::with_capacity(adj_exp as usize + 2);
        s.push_str(sign_str);
        for &ch in &digit_chars {
            s.push(ch);
        }
        let needed_zeros = (adj_exp as usize + 1).saturating_sub(digit_chars.len());
        for _ in 0..needed_zeros {
            s.push('0');
        }
        Ok(s)
    } else if (-4..0).contains(&adj_exp) {
        // Small fraction like 0.00123.
        let mut s = String::with_capacity(n + (-adj_exp) as usize + 3);
        s.push_str(sign_str);
        s.push_str("0.");
        let leading_zeros = (-adj_exp - 1) as usize;
        for _ in 0..leading_zeros {
            s.push('0');
        }
        for &ch in &digit_chars {
            s.push(ch);
        }
        // Trim trailing zeros.
        let trimmed = s.trim_end_matches('0');
        Ok(trimmed.to_string())
    } else {
        // Scientific notation: d1.d2d3...dn × 10^adj_exp.
        let mut s = String::with_capacity(n + 10);
        s.push_str(sign_str);
        s.push(digit_chars[0]);
        if n > 1 {
            s.push('.');
            for &ch in &digit_chars[1..] {
                s.push(ch);
            }
            // Trim trailing zeros in the fractional part.
            while s.ends_with('0') {
                s.pop();
            }
            if s.ends_with('.') {
                s.pop();
            }
        }
        s.push_str(&format!("e{adj_exp}"));
        Ok(s)
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Tests
// ═══════════════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::arena::Arena;

    /// Helper: evaluate and assert the result starts with expected prefix.
    fn assert_evalf_starts_with(arena: &Arena, expr: ExprId, digits: u32, prefix: &str) {
        let result = evalf(arena, expr, digits).unwrap();
        assert!(
            result.starts_with(prefix),
            "expected to start with '{prefix}', got: '{result}'"
        );
    }

    /// Helper: evaluate and assert exact string match.
    fn assert_evalf_eq(arena: &Arena, expr: ExprId, digits: u32, expected: &str) {
        let result = evalf(arena, expr, digits).unwrap();
        assert_eq!(result, expected, "evalf mismatch");
    }

    // ── Integers ────────────────────────────────────────────────────

    #[test]
    fn integer_zero() {
        let a = Arena::new();
        assert_evalf_eq(&a, a.zero, 10, "0");
    }

    #[test]
    fn integer_one() {
        let a = Arena::new();
        assert_evalf_eq(&a, a.one, 10, "1");
    }

    #[test]
    fn integer_negative_one() {
        let a = Arena::new();
        assert_evalf_eq(&a, a.neg_one, 10, "-1");
    }

    #[test]
    fn integer_five() {
        let mut a = Arena::new();
        let five = a.int(5);
        assert_evalf_eq(&a, five, 10, "5");
    }

    #[test]
    fn integer_large() {
        let mut a = Arena::new();
        let n = a.int(123456);
        assert_evalf_eq(&a, n, 10, "123456");
    }

    // ── Rationals ───────────────────────────────────────────────────

    #[test]
    fn rational_half() {
        let mut a = Arena::new();
        let half = a.rational(1, 2);
        assert_evalf_eq(&a, half, 10, "0.5");
    }

    #[test]
    fn rational_one_third() {
        let mut a = Arena::new();
        let third = a.rational(1, 3);
        assert_evalf_starts_with(&a, third, 10, "0.333333333");
    }

    #[test]
    fn rational_negative() {
        let mut a = Arena::new();
        let r = a.rational(-3, 4);
        assert_evalf_starts_with(&a, r, 10, "-0.75");
    }

    // ── Constants ───────────────────────────────────────────────────

    #[test]
    fn constant_pi_15_digits() {
        let a = Arena::new();
        assert_evalf_starts_with(&a, a.pi, 15, "3.14159265358979");
    }

    #[test]
    fn constant_pi_50_digits() {
        let a = Arena::new();
        let result = evalf(&a, a.pi, 50).unwrap();
        assert!(
            result.starts_with("3.1415926535897932384626433832795"),
            "pi to 50 digits: {result}"
        );
    }

    #[test]
    fn constant_e_15_digits() {
        let a = Arena::new();
        assert_evalf_starts_with(&a, a.e_const, 15, "2.71828182845905");
    }

    // ── Arithmetic ──────────────────────────────────────────────────

    #[test]
    fn add_integers() {
        let mut a = Arena::new();
        let two = a.int(2);
        let three = a.int(3);
        let expr = a.add(&[two, three]);
        assert_evalf_eq(&a, expr, 10, "5");
    }

    #[test]
    fn mul_integers() {
        let mut a = Arena::new();
        let two = a.int(2);
        let three = a.int(3);
        let expr = a.mul(&[two, three]);
        assert_evalf_eq(&a, expr, 10, "6");
    }

    #[test]
    fn pow_integer() {
        let mut a = Arena::new();
        let two = a.int(2);
        let ten = a.int(10);
        let expr = a.pow(two, ten);
        assert_evalf_eq(&a, expr, 10, "1024");
    }

    #[test]
    fn pow_negative_exponent() {
        let mut a = Arena::new();
        let two = a.int(2);
        let neg_one = a.int(-1);
        let expr = a.pow(two, neg_one);
        assert_evalf_eq(&a, expr, 10, "0.5");
    }

    #[test]
    fn pi_plus_one() {
        let mut a = Arena::new();
        let pi = a.pi;
        let one = a.one;
        let expr = a.add(&[pi, one]);
        assert_evalf_starts_with(&a, expr, 15, "4.14159265358979");
    }

    // ── Transcendental functions ─────────────────────────────────────

    #[test]
    fn sin_zero() {
        let mut a = Arena::new();
        let zero = a.zero;
        let expr = a.sin(zero);
        assert_evalf_eq(&a, expr, 10, "0");
    }

    #[test]
    fn cos_zero() {
        let mut a = Arena::new();
        let zero = a.zero;
        let expr = a.cos(zero);
        assert_evalf_eq(&a, expr, 10, "1");
    }

    #[test]
    fn exp_zero() {
        let mut a = Arena::new();
        let zero = a.zero;
        let expr = a.exp(zero);
        assert_evalf_eq(&a, expr, 10, "1");
    }

    #[test]
    fn exp_one() {
        let mut a = Arena::new();
        let one = a.one;
        let expr = a.exp(one);
        assert_evalf_starts_with(&a, expr, 15, "2.71828182845905");
    }

    #[test]
    fn ln_one() {
        let mut a = Arena::new();
        let one = a.one;
        let expr = a.ln(one);
        assert_evalf_eq(&a, expr, 10, "0");
    }

    #[test]
    fn ln_e() {
        let mut a = Arena::new();
        let e = a.e_const;
        let expr = a.ln(e);
        // ln(e) should be 1, or very close.
        let result = evalf(&a, expr, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(999.0);
        assert!(
            (val - 1.0).abs() < 1e-10,
            "ln(e) should be ~1, got: {result}"
        );
    }

    #[test]
    fn sqrt_four() {
        let mut a = Arena::new();
        let four = a.int(4);
        let expr = a.sqrt(four);
        assert_evalf_eq(&a, expr, 10, "2");
    }

    #[test]
    fn sqrt_two_30_digits() {
        let mut a = Arena::new();
        let two = a.int(2);
        let expr = a.sqrt(two);
        assert_evalf_starts_with(&a, expr, 30, "1.4142135623730950488");
    }

    #[test]
    fn sin_pi_is_near_zero() {
        let mut a = Arena::new();
        let pi = a.pi;
        let expr = a.sin(pi);
        let result = evalf(&a, expr, 20).unwrap();
        // sin(pi) is mathematically 0, numerically very small.
        let val: f64 = result.parse().unwrap_or(999.0);
        assert!(val.abs() < 1e-15, "sin(pi) should be ~0, got: {result}");
    }

    // ── Neg and Abs ─────────────────────────────────────────────────

    #[test]
    fn neg_pi() {
        let mut a = Arena::new();
        let pi = a.pi;
        let expr = a.neg(pi);
        assert_evalf_starts_with(&a, expr, 10, "-3.14159265");
    }

    #[test]
    fn abs_neg_pi() {
        let mut a = Arena::new();
        let pi = a.pi;
        let neg_pi = a.neg(pi);
        let expr = a.abs(neg_pi);
        assert_evalf_starts_with(&a, expr, 10, "3.14159265");
    }

    #[test]
    fn abs_negative_integer() {
        let mut a = Arena::new();
        let neg_five = a.int(-5);
        let expr = a.abs(neg_five);
        assert_evalf_eq(&a, expr, 10, "5");
    }

    // ── Error cases ─────────────────────────────────────────────────

    #[test]
    fn free_symbol_errors() {
        let mut a = Arena::new();
        let x = a.symbol("x");
        let result = evalf(&a, x, 10);
        assert!(result.is_err(), "evalf of free symbol should error");
    }

    #[test]
    fn infinity_errors() {
        let a = Arena::new();
        let result = evalf(&a, a.infinity, 10);
        assert!(result.is_err(), "evalf of infinity should error");
    }

    #[test]
    fn nan_errors() {
        let a = Arena::new();
        let result = evalf(&a, a.nan, 10);
        assert!(result.is_err(), "evalf of NaN should error");
    }

    #[test]
    fn imaginary_unit_works() {
        let a = Arena::new();
        let result = evalf(&a, a.i_unit, 10);
        assert!(result.is_ok(), "evalf of i should work now");
        let s = result.unwrap();
        assert!(
            s.contains("i") || s.contains("I"),
            "should display as imaginary: {s}"
        );
    }

    // ── Complex number tests ────────────────────────────────────────

    #[test]
    fn evalf_one_plus_i() {
        let mut a = Arena::new();
        let one = a.one;
        let i = a.i_unit;
        let expr = a.add(&[one, i]);
        let result = evalf(&a, expr, 10);
        assert!(result.is_ok(), "evalf(1+i) should work: {:?}", result.err());
        let s = result.unwrap();
        assert!(
            s.contains("i") || s.contains("I"),
            "1+i should contain 'i': {s}"
        );
    }

    #[test]
    fn evalf_exp_i_pi() {
        // e^(i*pi) ≈ -1
        let mut a = Arena::new();
        let i = a.i_unit;
        let pi = a.pi;
        let i_times_pi = a.mul(&[i, pi]);
        let expr = a.exp(i_times_pi);
        let result = evalf(&a, expr, 15);
        assert!(
            result.is_ok(),
            "evalf(exp(i*pi)) should work: {:?}",
            result.err()
        );
        let s = result.unwrap();
        let val: f64 = s.parse().unwrap_or(999.0);
        assert!(
            (val - (-1.0)).abs() < 1e-10,
            "exp(i*pi) should be ~-1, got: {s}"
        );
    }

    #[test]
    fn evalf_i_squared() {
        // i^2 = -1 (may be canonicalized by the arena)
        let mut a = Arena::new();
        let i = a.i_unit;
        let two = a.int(2);
        let expr = a.pow(i, two);
        let result = evalf(&a, expr, 10);
        assert!(result.is_ok(), "evalf(i^2) should work: {:?}", result.err());
        let s = result.unwrap();
        let val: f64 = s.parse().unwrap_or(999.0);
        assert!((val - (-1.0)).abs() < 1e-10, "i^2 should be -1, got: {s}");
    }

    #[test]
    fn evalf_sqrt_neg_one() {
        // sqrt(-1) = (-1)^(1/2) should give i
        let mut a = Arena::new();
        let neg_one = a.neg_one;
        let expr = a.sqrt(neg_one);
        let result = evalf(&a, expr, 10);
        assert!(
            result.is_ok(),
            "evalf(sqrt(-1)) should work: {:?}",
            result.err()
        );
        let s = result.unwrap();
        assert!(
            s.contains("i") || s.contains("I"),
            "sqrt(-1) should be imaginary: {s}"
        );
    }

    #[test]
    fn evalf_abs_3_plus_4i() {
        // |3 + 4i| = 5
        let mut a = Arena::new();
        let three = a.int(3);
        let four = a.int(4);
        let i = a.i_unit;
        let four_i = a.mul(&[four, i]);
        let sum = a.add(&[three, four_i]);
        let expr = a.abs(sum);
        let result = evalf(&a, expr, 10);
        assert!(
            result.is_ok(),
            "evalf(|3+4i|) should work: {:?}",
            result.err()
        );
        let s = result.unwrap();
        let val: f64 = s.parse().unwrap_or(999.0);
        assert!((val - 5.0).abs() < 1e-10, "|3+4i| should be 5, got: {s}");
    }

    // ── Composite expressions ───────────────────────────────────────

    #[test]
    fn polynomial_at_value() {
        // Evaluate x^2 + 2*x + 1 at x=3 → 16.
        // We substitute first, then evalf.
        let mut a = Arena::new();
        let x = a.symbol("x");
        let two = a.int(2);
        let x_sq = a.pow(x, two);
        let two_x = a.mul(&[two, x]);
        let expr = a.add(&[x_sq, two_x, a.one]);

        // Substitute x → 3.
        let three = a.int(3);
        let evaluated = crate::transforms::subs::subs(&mut a, expr, x, three);
        assert_evalf_eq(&a, evaluated, 10, "16");
    }

    #[test]
    fn sin_cos_identity() {
        // sin^2(1) + cos^2(1) should be very close to 1.
        let mut a = Arena::new();
        let one = a.one;
        let two = a.int(2);
        let sin_1 = a.sin(one);
        let cos_1 = a.cos(one);
        let sin_sq = a.pow(sin_1, two);
        let cos_sq = a.pow(cos_1, two);
        let expr = a.add(&[sin_sq, cos_sq]);
        let result = evalf(&a, expr, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(0.0);
        assert!(
            (val - 1.0).abs() < 1e-12,
            "sin^2(1) + cos^2(1) should be ~1, got: {result}"
        );
    }

    // ── Idempotence ─────────────────────────────────────────────────

    #[test]
    fn same_precision_same_result() {
        let a = Arena::new();
        let r1 = evalf(&a, a.pi, 20).unwrap();
        let r2 = evalf(&a, a.pi, 20).unwrap();
        assert_eq!(r1, r2, "same precision should give same result");
    }

    // ── Bessel function evaluation ─────────────────────────────────

    /// The exact-integer coefficients of `Y_n`, `K_n` and `ψ⁽ⁿ⁾` (0.34) round
    /// to the same BigFloats as the reduced `Ratio` recurrences before them:
    /// the same digits, without the gcds.
    /// The term-by-term Jacobi sum (0.34) agrees with the sum that recomputed
    /// every coefficient (before 0.34, kept here as the reference), also for
    /// a negative integer `a` (leading terms 0) and at `x = ±1`.
    #[test]
    fn jacobi_term_by_term_matches_the_explicit_sum() {
        let rm = RoundingMode::ToEven;
        let mut cc = Consts::new().unwrap();
        let prec = 128;
        let reference = |deg: usize, a: &BigFloat, b: &BigFloat, x: &BigFloat| -> BigFloat {
            let wp = prec + 32 + 2 * deg;
            let one = BigFloat::from_i32(1, wp);
            let two = BigFloat::from_i32(2, wp);
            let lo = x.sub(&one, wp, rm).div(&two, wp, rm);
            let hi = x.add(&one, wp, rm).div(&two, wp, rm);
            let shifted = |p: &BigFloat, lo_j: usize, hi_j: usize| -> BigFloat {
                let mut acc = one.clone();
                for j in lo_j..=hi_j {
                    acc = acc.mul(&p.add(&BigFloat::from_i128(j as i128, wp), wp, rm), wp, rm);
                }
                acc
            };
            let mut sum = BigFloat::new(wp);
            for s in 0..=deg {
                let pa = shifted(a, s + 1, deg);
                let pb = shifted(b, deg - s + 1, deg);
                let d =
                    ratio_to_bigfloat(&(factorial_bigint(deg - s) * factorial_bigint(s)), wp, rm);
                let term = pa
                    .mul(&pb, wp, rm)
                    .div(&d, wp, rm)
                    .mul(&lo.powi(s, wp, rm), wp, rm)
                    .mul(&hi.powi(deg - s, wp, rm), wp, rm);
                sum = sum.add(&term, wp, rm);
            }
            round_to(sum, prec, rm)
        };
        let q =
            |n: i32, d: i32| BigFloat::from_i32(n, 256).div(&BigFloat::from_i32(d, 256), 256, rm);
        for deg in [1usize, 2, 5, 17, 60] {
            for (a, b) in [
                (q(1, 3), q(1, 5)),
                (q(-3, 1), q(2, 7)),
                (q(-1, 1), q(-2, 1)),
                (q(5, 2), q(-7, 3)),
            ] {
                for x in [q(1, 3), q(-9, 10), q(1, 1), q(-1, 1), q(3, 1), q(-5, 2)] {
                    let n = BigFloat::from_u64(deg as u64, 64);
                    let got = arb_jacobi(&n, &a, &b, &x, prec, rm, &mut cc).unwrap();
                    let want = reference(deg, &a, &b, &x);
                    let diff = got.sub(&want, prec, rm).abs();
                    let ok = diff.is_zero()
                        || match (diff.exponent(), want.exponent()) {
                            (Some(d), Some(w)) => i64::from(d) < i64::from(w) - (prec as i64 - 4),
                            _ => false,
                        };
                    assert!(ok, "deg={deg} a={a} b={b} x={x}: {got} vs {want}");
                }
            }
        }
    }

    #[test]
    fn exact_coefficients_match_the_ratio_recurrences() {
        let rm = RoundingMode::ToEven;
        for (n, wp) in (1..60usize).flat_map(|n| [(n, 64), (n, 160)]) {
            let mut f = Ratio::<BigInt>::from_integer(BigInt::from(1));
            for i in 2..n {
                f *= Ratio::from_integer(BigInt::from(i as u64));
            }
            let mut g = NeumannCoefficients::new(n);
            for k in 0..n {
                if k > 0 {
                    f /= Ratio::from_integer(BigInt::from(((n - k) * k) as u64));
                }
                assert_eq!(g.next(wp, rm), ratio_to_bigfloat(&f, wp, rm), "n={n} k={k}");
            }
            let mut fact = Ratio::<BigInt>::from_integer(BigInt::from(1));
            for i in 2..=n {
                fact *= Ratio::from_integer(BigInt::from(i as u64));
            }
            assert_eq!(factorial_exact(n), fact);
        }
        for k in 1..40 {
            let b = bernoulli::even(k);
            for r in [1u64, 2, 6, 30, 42, 1155, 1_000_003, 510_510] {
                let r = BigInt::from(r) * BigInt::from(k as u64 * 7 + 1);
                assert_eq!(times_integer(&b, &r), &b * Ratio::from_integer(r.clone()));
            }
        }
    }

    #[test]
    fn bessel_j0_at_zero() {
        // J_0(0) = 1
        let mut a = Arena::new();
        let zero = a.zero;
        let j0_0 = a.besselj(zero, zero);
        let result = evalf(&a, j0_0, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(f64::NAN);
        assert!(
            (val - 1.0).abs() < 1e-10,
            "J_0(0) should be 1.0, got {result}"
        );
    }

    #[test]
    fn bessel_j0_at_one() {
        // J_0(1) ≈ 0.7651976865579666
        let mut a = Arena::new();
        let zero = a.zero;
        let one = a.one;
        let j0_1 = a.besselj(zero, one);
        let result = evalf(&a, j0_1, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(f64::NAN);
        assert!(
            (val - 0.7651976865579666).abs() < 1e-8,
            "J_0(1) should be ~0.7652, got {result}"
        );
    }

    #[test]
    fn bessel_j1_at_zero() {
        // J_1(0) = 0
        let mut a = Arena::new();
        let one = a.one;
        let zero = a.zero;
        let j1_0 = a.besselj(one, zero);
        let result = evalf(&a, j1_0, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(f64::NAN);
        assert!(val.abs() < 1e-10, "J_1(0) should be 0, got {result}");
    }

    #[test]
    fn bessel_j1_at_one() {
        // J_1(1) ≈ 0.44005058574493355
        let mut a = Arena::new();
        let one = a.one;
        let j1_1 = a.besselj(one, one);
        let result = evalf(&a, j1_1, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(f64::NAN);
        assert!(
            (val - 0.44005058574493355).abs() < 1e-8,
            "J_1(1) should be ~0.4401, got {result}"
        );
    }

    #[test]
    fn bessel_y0_at_one() {
        // Y_0(1) ≈ 0.08825696421567696
        let mut a = Arena::new();
        let zero = a.zero;
        let one = a.one;
        let y0_1 = a.bessely(zero, one);
        let result = evalf(&a, y0_1, 15).unwrap();
        let val: f64 = result.parse().unwrap_or(f64::NAN);
        assert!(
            (val - 0.08825696421567696).abs() < 1e-6,
            "Y_0(1) should be ~0.0883, got {result}"
        );
    }

    // ── 0.2: named constants ───────────────────────────────────────────────

    #[test]
    fn euler_gamma_and_catalan_high_precision() {
        let a = Arena::new();
        assert_evalf_starts_with(
            &a,
            a.euler_gamma,
            60,
            "0.57721566490153286060651209008240243104215933593992359880576",
        );
        assert_evalf_starts_with(
            &a,
            a.catalan,
            60,
            "0.91596559417721901505460351493238411077414937428167213426649",
        );
        assert_evalf_starts_with(
            &a,
            a.golden_ratio,
            40,
            "1.61803398874989484820458683436563811772",
        );
    }

    #[test]
    fn bigint_to_bigfloat_is_exact_for_huge_integers() {
        // 2^200 + 1 is far beyond i128; its BigFloat must keep all bits.
        let n = (BigInt::from(1) << 200) + BigInt::from(1);
        let bf = crate::base::numeric::bigint_to_bigfloat(&n, 256);
        let two200 = BigFloat::from_i32(2, 256).powi(200, 256, RoundingMode::ToEven);
        let diff = bf.sub(&two200, 256, RoundingMode::ToEven);
        assert_eq!(diff, BigFloat::from_i32(1, 256));
    }

    #[test]
    fn bf_pow_handles_exactly_representable_results() {
        // BigFloat::pow would hang on 4^(1/2) = 2; bf_pow must not.
        let mut cc = Consts::new().unwrap();
        let rm = RoundingMode::ToEven;
        let four = BigFloat::from_i32(4, 160);
        let half = BigFloat::from_f64(0.5, 160);
        let r = bf_pow(&four, &half, 160, rm, &mut cc);
        let diff = r.sub(&BigFloat::from_i32(2, 160), 160, rm);
        assert!(
            diff.is_zero() || diff.exponent().is_none_or(|e| e < -140),
            "4^0.5 = {r}"
        );
        // integer exponent path
        let three = BigFloat::from_i32(3, 160);
        let r = bf_pow(&three, &BigFloat::from_i32(5, 160), 160, rm, &mut cc);
        assert_eq!(r, BigFloat::from_i32(243, 160));
        let r = bf_pow(&three, &BigFloat::from_i32(-1, 160), 160, rm, &mut cc);
        let back = r.mul(&three, 160, rm);
        let d = back.sub(&BigFloat::from_i32(1, 160), 160, rm);
        assert!(d.is_zero() || d.exponent().is_none_or(|e| e < -140));
    }

    // ── 0.2: special functions ──────────────────────────────────────────────

    #[test]
    fn si_ci_ei_li_at_one_and_two() {
        let mut a = Arena::new();
        let one = a.one;
        let two = a.int(2);
        let si = a.si(one);
        assert_evalf_starts_with(&a, si, 20, "0.94608307036718301494");
        let ci = a.ci(one);
        assert_evalf_starts_with(&a, ci, 20, "0.33740392290096813466");
        let ei = a.ei(one);
        assert_evalf_starts_with(&a, ei, 20, "1.8951178163559367555");
        let li = a.li(two);
        assert_evalf_starts_with(&a, li, 20, "1.0451637801174927848");
    }

    #[test]
    fn si_asymptotic_and_series_regimes_agree() {
        // Evaluate Si(40) at two precisions: at low precision the asymptotic
        // expansion is used (40 > 160·ln2 ≈ 111 is false …), so force the
        // regimes by comparing against the same value at higher precision
        // where the series is used.
        let mut a = Arena::new();
        let x = a.int(200);
        let si = a.si(x);
        let lo = evalf(&a, si, 12).unwrap(); // asymptotic (200 > 128·ln2)
        let hi = evalf(&a, si, 120).unwrap(); // series (200 < 472·ln2)
        assert!(hi.starts_with(&lo[..12]), "{lo} vs {hi}");
    }

    #[test]
    fn zeta_borwein_and_functional_equation() {
        let mut a = Arena::new();
        let three = a.int(3);
        let z3 = a.zeta(three);
        assert_evalf_starts_with(&a, z3, 30, "1.20205690315959428539973816151");
        let half = a.rational(1, 2);
        let zh = a.zeta(half);
        assert_evalf_starts_with(&a, zh, 20, "-1.4603545088095868129");
        // ζ(−5/2) > 0 (ζ is positive on (−4, −2); ζ(−3) = 1/120).
        let neg = a.rational(-5, 2);
        let zn = a.zeta(neg);
        assert_evalf_starts_with(&a, zn, 15, "0.00851692877785");
        // ζ(−1/2) < 0
        let neg_half = a.rational(-1, 2);
        let znh = a.zeta(neg_half);
        assert_evalf_starts_with(&a, znh, 15, "-0.20788622497735");
    }

    #[test]
    fn polygamma_matches_trigamma_closed_forms() {
        let mut a = Arena::new();
        // Build the node structurally so the exact folding does not kick in.
        let one = a.one;
        let x = a.rational(7, 3);
        let pg = a.intern(ExprNode::Polygamma(one, x));
        assert_evalf_starts_with(&a, pg, 20, "0.53309712542709408179");
        // ψ'(1/2) = π²/2 through the numerical path
        let half = a.rational(1, 2);
        let pg_half = a.intern(ExprNode::Polygamma(one, half));
        assert_evalf_starts_with(&a, pg_half, 20, "4.9348022005446793094");
    }

    #[test]
    fn bessel_i_k_reference() {
        let mut a = Arena::new();
        let zero = a.zero;
        let one = a.one;
        let i0 = a.besseli(zero, one);
        assert_evalf_starts_with(&a, i0, 20, "1.2660658777520083356");
        let k0 = a.besselk(zero, one);
        assert_evalf_starts_with(&a, k0, 20, "0.42102443824070833334");
        let k1 = a.besselk(one, one);
        assert_evalf_starts_with(&a, k1, 20, "0.60190723019723457474");
    }

    #[test]
    fn orthogonal_polynomials_large_degree() {
        let mut a = Arena::new();
        let n = a.int(100);
        let third = a.rational(1, 3);
        let t = a.chebyshev_t(n, third);
        let s = evalf(&a, t, 15).unwrap();
        let v: f64 = s.parse().unwrap();
        let expected = (100.0 * (1.0f64 / 3.0).acos()).cos();
        assert!((v - expected).abs() < 1e-12, "{v} vs {expected}");
        let p = a.legendre(n, a.one);
        assert_evalf_starts_with(&a, p, 10, "1");
    }

    #[test]
    fn complex_nodes_evaluate_numerically() {
        let mut a = Arena::new();
        let z = a.symbol("z");
        let re_z = a.intern(ExprNode::Re(z));
        let arg_z = a.intern(ExprNode::Arg(z));
        let conj_z = a.intern(ExprNode::Conjugate(z));
        let three = a.int(3);
        let four = a.int(4);
        let four_i = a.mul(&[four, a.i_unit]);
        let w = a.add(&[three, four_i]);
        // Substitute structurally *without* refolding: intern the nodes
        // directly on w.
        let _ = re_z;
        let re_w = a.intern(ExprNode::Re(w));
        let arg_w = a.intern(ExprNode::Arg(w));
        let conj_w = a.intern(ExprNode::Conjugate(w));
        let _ = (arg_z, conj_z);
        assert_eq!(evalf(&a, re_w, 10).unwrap(), "3");
        assert_evalf_starts_with(&a, arg_w, 15, "0.92729521800161");
        let s = evalf(&a, conj_w, 10).unwrap();
        assert!(s.contains('3') && s.contains('4') && s.contains('-'), "{s}");
    }

    /// A `RootSum` over a polynomial with repeated roots counts each root
    /// with its multiplicity.  Before 0.29 it was `PrecisionExhausted`: the
    /// inclusion disks of a repeated root overlap, so no root was certified.
    #[test]
    fn rootsum_over_repeated_roots_counts_multiplicity() {
        let mut a = Arena::new();
        let x = a.symbol("x");
        let two = a.int(2);
        let three = a.int(3);
        let minus_two = a.int(-2);
        let minus_one = a.int(-1);
        // (x² − 2)², body 1/(x + 3).
        let x2 = a.pow(x, two);
        let q = a.add(&[x2, minus_two]);
        let poly = a.pow(q, two);
        let xp3 = a.add(&[x, three]);
        let body = a.pow(xp3, minus_one);
        let rs = a.intern(ExprNode::RootSum(poly, body, x));
        // mpmath: mp.dps=50; 2*(1/(3+sqrt(2)) + 1/(3-sqrt(2)))
        //         = 1.71428571428571428571428571429
        assert_evalf_eq(&a, rs, 20, "1.7142857142857142857");
        // (x² + 1)²·(x − 3), body exp(x).
        let one = a.int(1);
        let x2p1 = a.add(&[x2, one]);
        let sq = a.pow(x2p1, two);
        let minus_three = a.int(-3);
        let xm3 = a.add(&[x, minus_three]);
        let poly = a.mul(&[sq, xm3]);
        let body = a.intern(ExprNode::Exp(x));
        let rs = a.intern(ExprNode::RootSum(poly, body, x));
        // mpmath: mp.dps=50; 2*(exp(1j)+exp(-1j)) + exp(3)
        //         = (22.2467461466602266105322760844 + 0.0j)
        assert_evalf_eq(&a, rs, 20, "22.246746146660226611");
    }

    // ── 0.11.1 special-function fixes (direct numeric paths that `eval`
    //    would otherwise fold away) ──────────────────────────────────────────

    fn apply(a: &mut Arena, f: LibFn, args: &[ExprId]) -> ExprId {
        a.lib_apply(f, args)
    }

    #[test]
    fn erfc_node_large_argument_is_relative_precision() {
        let mut a = Arena::new();
        // mpmath 1.3: erfc(7) = 4.18382560777941439861401e-23
        let seven = a.int(7);
        let e7 = a.erfc(seven);
        assert_evalf_starts_with(&a, e7, 16, "4.183825607779414e-23");
        // mpmath 1.3: erfc(10) = 2.088487583762544757000786294957788611560818119321163727e-45
        let ten = a.int(10);
        let e10 = a.erfc(ten);
        assert_evalf_starts_with(
            &a,
            e10,
            50,
            "2.0884875837625447570007862949577886115608181193212e-45",
        );
        // mpmath 1.3: erfc(30) = 2.564656203756111600033397e-393 (asymptotic branch)
        let thirty = a.int(30);
        let e30 = a.erfc(thirty);
        assert_evalf_starts_with(&a, e30, 16, "2.564656203756112e-393");
        // mpmath 1.3: erfc(-3) = 1.999977909503001414558627 (no cancellation)
        let m3 = a.int(-3);
        let em3 = a.erfc(m3);
        assert_evalf_starts_with(&a, em3, 16, "1.999977909503001");
    }

    #[test]
    fn erf_taylor_branch_carries_cancellation_guard_bits() {
        let mut a = Arena::new();
        // mpmath 1.3: erf(7.4) = 0.99999999999999999999999987516143536
        let x = a.rational(74, 10);
        let e = a.erf(x);
        assert_evalf_starts_with(&a, e, 30, "0.999999999999999999999999875161");
        // mpmath 1.3: erf(10) = 0.9999999999999999999999999999999999999999999979115124162
        // (50 digits: the Taylor terms peak near e^{100} ≈ 2^{144})
        let ten = a.int(10);
        let e10 = a.erf(ten);
        assert_evalf_starts_with(
            &a,
            e10,
            50,
            "0.99999999999999999999999999999999999999999999791151",
        );
        // mpmath 1.3: erf(3) = 0.999977909503001414558627223870417679620152293
        let three = a.int(3);
        let e3 = a.erf(three);
        assert_evalf_starts_with(&a, e3, 40, "0.999977909503001414558627223870417679620");
    }

    #[test]
    fn polylog_at_minus_one_is_minus_eta_for_all_s() {
        let mut a = Arena::new();
        let neg_one = a.neg_one;
        // mpmath 1.3: polylog(1/2, -1) = -0.6048986434216303702472659142359555
        let half = a.rational(1, 2);
        let li = apply(&mut a, LibFn::PolyLog, &[half, neg_one]);
        assert_evalf_starts_with(&a, li, 30, "-0.60489864342163037024726591423");
        // mpmath 1.3: polylog(1, -1) = -ln 2 = -0.69314718055994530941723212145817657
        let one = a.one;
        let li1 = apply(&mut a, LibFn::PolyLog, &[one, neg_one]);
        assert_evalf_starts_with(&a, li1, 30, "-0.69314718055994530941723212145");
        // mpmath 1.3: polylog(-1/2, -1) = -0.38010481260968401677754215655180836
        let neg_half = a.rational(-1, 2);
        let lim = apply(&mut a, LibFn::PolyLog, &[neg_half, neg_one]);
        assert_evalf_starts_with(&a, lim, 30, "-0.38010481260968401677754215655");
        // mpmath 1.3: polylog(3/2, -1) = -0.76514702462540794536726875860347818
        let three_halves = a.rational(3, 2);
        let li32 = apply(&mut a, LibFn::PolyLog, &[three_halves, neg_one]);
        assert_evalf_starts_with(&a, li32, 30, "-0.76514702462540794536726875860");
        // z = +1 still diverges for s ≤ 1
        let one_id = a.one;
        let div = apply(&mut a, LibFn::PolyLog, &[half, one_id]);
        assert!(evalf(&a, div, 16).is_err());
    }

    #[test]
    fn dirichlet_eta_near_one_uses_alternating_sum() {
        let mut a = Arena::new();
        // mpmath 1.3: altzeta(1 + 1e-20) = 0.69314718055994530941883081049560088
        let ten = a.int(10);
        let e20 = a.int(-20);
        let tiny = a.pow(ten, e20);
        let s = a.add(&[a.one, tiny]);
        let eta = apply(&mut a, LibFn::DirichletEta, &[s]);
        assert_evalf_starts_with(&a, eta, 30, "0.69314718055994530941883081049");
        // mpmath 1.3: altzeta(1 - 1e-20) = 0.69314718055994530941563343242075226
        let s2 = a.sub(a.one, tiny);
        let eta2 = apply(&mut a, LibFn::DirichletEta, &[s2]);
        assert_evalf_starts_with(&a, eta2, 30, "0.69314718055994530941563343242");
        // Exactly 1 through the numeric path: mpmath altzeta(1) = ln 2
        let one = a.one;
        let eta1 = apply(&mut a, LibFn::DirichletEta, &[one]);
        assert_evalf_starts_with(&a, eta1, 30, "0.69314718055994530941723212145");
        // s ≤ 0 still goes through ζ: mpmath altzeta(-1/2) = 0.38010481260968401677754215655180836
        let neg_half = a.rational(-1, 2);
        let etam = apply(&mut a, LibFn::DirichletEta, &[neg_half]);
        assert_evalf_starts_with(&a, etam, 30, "0.38010481260968401677754215655");
    }

    #[test]
    fn airy_derivatives_at_exact_zero() {
        let mut a = Arena::new();
        let zero = a.zero;
        // mpmath 1.3: airyai(0, derivative=1) = -0.25881940379280679840518356018920396
        let aip = apply(&mut a, LibFn::AiryAiPrime, &[zero]);
        assert_evalf_starts_with(&a, aip, 30, "-0.25881940379280679840518356018");
        // mpmath 1.3: airybi(0, derivative=1) = 0.44828835735382635791482371039882839
        let bip = apply(&mut a, LibFn::AiryBiPrime, &[zero]);
        assert_evalf_starts_with(&a, bip, 30, "0.44828835735382635791482371039");
    }

    #[test]
    fn polylog_series_bound_accounts_for_negative_order() {
        // s ≥ 0: the classic wp·ln 2 / (−ln|z|) bound (+20).
        let n = polylog_series_terms(2.0, 0.5, 100);
        assert!((120..=122).contains(&n), "{n}");
        // s < 0: |z|^k k^{|s|} peaks near k = |s|/(−ln|z|) before decaying.
        let n = polylog_series_terms(-40.5, 0.5, 132);
        let a = -(0.5f64).ln();
        let k = (n - 20) as f64;
        assert!(
            k * a - 40.5 * k.ln() >= 132.0 * std::f64::consts::LN_2,
            "{n}"
        );
        assert!(n > 200, "{n}");
    }
}