num-valid 0.3.3

A robust numerical library providing validated types for real and complex numbers to prevent common floating-point errors like NaN propagation. Features a generic, layered architecture with support for native f64 and optional arbitrary-precision arithmetic.
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
#![deny(rustdoc::broken_intra_doc_links)]
#![feature(box_patterns)]
#![feature(error_generic_member_access)]
#![feature(trait_alias)]

//! [`num-valid`](crate) is a Rust library designed for robust, generic, and high-performance numerical computation.
//! It provides a safe and extensible framework for working with both real and complex numbers, addressing the challenges
//! of floating-point arithmetic by ensuring correctness and preventing common errors like `NaN` propagation.
//!
//! # Key Features \& Architecture
//!
//! - **Safety by Construction with Validated Types:** Instead of using raw primitives like [`f64`] or [`Complex<f64>`](num::Complex)
//!   directly, [`num-valid`](crate) encourages the use of validated wrappers like [`RealValidated`]
//!   and [`ComplexValidated`]. These types guarantee that the value they hold is always valid (e.g.,
//!   finite) according to a specific policy, eliminating entire classes of numerical bugs.
//!
//! - **Enhanced Type Safety with Hashing Support:** Types validated with policies that guarantee
//!   finite values (like [`Native64StrictFinite`]) automatically
//!   implement [`Eq`] and [`Hash`]. This enables their use as keys in [`HashMap`](std::collections::HashMap) and other
//!   hash-based collections, while maintaining compatibility with the library's [`PartialOrd`]-based
//!   comparison functions. The hashing implementation properly handles IEEE 754 floating-point
//!   edge cases and ensures that mathematically equal values produce identical hash codes.
//!
//! - **Support for Real and Complex Numbers:** The library supports both real and complex numbers,
//!   with specific validation policies for each type.
//!
//! - **Layered and Extensible Design:** The library has a well-defined, layered, and highly generic architecture.
//!   It abstracts the concept of a "numerical kernel" (the underlying number representation and its operations) from the high-level mathematical traits.
//!
//!   The architecture can be understood in four main layers:
//!   - **Layer 1: Raw Trait Contracts** ([`kernels`] module):
//!     - The [`RawScalarTrait`], [`RawRealTrait`], and [`RawComplexTrait`](crate::kernels::RawComplexTrait) define the low-level, "unchecked" contract
//!       for any number type.
//!     - These traits are the foundation, providing a standard set of `unchecked_*` methods.
//!     - The contract is that the caller must guarantee the validity of inputs. This is a strong design choice, separating the raw, potentially unsafe operations from the validated, safe API.
//!
//!     This design separates the pure, high-performance computational logic from the safety and validation logic.
//!     It creates a clear, minimal contract for backend implementors and allows the validated wrappers in Layer 3
//!     to be built on a foundation of trusted, high-speed operations.
//!
//!   - **Layer 2: Validation Policies** ([`core::policies`] module):
//!     - The [`NumKernel`] trait is the bridge between the raw types and the validated wrappers.
//!     - It bundles together the raw real/complex types and their corresponding validation policies
//!       (e.g., [`Native64StrictFinite`], [`Native64StrictFiniteInDebug`],
//!       etc.). This allows the entire behavior of the validated types to be configured with a single generic parameter.
//!
//!     It acts as the central policy configuration point. By choosing a [`NumKernel`], a user selects both a
//!     numerical backend (e.g., [`f64`]/[`Complex<f64>`] or [`rug::Float`](https://docs.rs/rug/latest/rug/struct.Float.html)/[`rug::Complex`](https://docs.rs/rug/latest/rug/struct.Complex.html)) and a set of validation policies (e.g., [`StrictFinitePolicy`](crate::core::policies::StrictFinitePolicy)
//!     vs. [`DebugValidationPolicy`](crate::core::policies::DebugValidationPolicy)) for real and complex numbers,
//!     with a single generic parameter. This dramatically simplifies writing generic code that can be configured for
//!     different safety and performance trade-offs.
//!
//!     **Policy Comparison:**
//!
//!     | Type Alias | Policy | Debug Build | Release Build | Use Case |
//!     |------------|--------|-------------|---------------|----------|
//!     | [`RealNative64StrictFinite`] | [`StrictFinitePolicy`](crate::core::policies::StrictFinitePolicy) | ✅ Validates | ✅ Validates | Safety-critical code, HashMap keys |
//!     | [`RealNative64StrictFiniteInDebug`] | [`DebugValidationPolicy`](crate::core::policies::DebugValidationPolicy) | ✅ Validates | ❌ No validation | Performance-critical hot paths |
//!     | `RealRugStrictFinite<P>` | [`StrictFinitePolicy`](crate::core::policies::StrictFinitePolicy) | ✅ Validates | ✅ Validates | High-precision calculations |
//!
//!     **Key Differences:**
//!     - **StrictFinite**: Always validates, implements [`Eq`] + [`Hash`] (safe for [`HashMap`](std::collections::HashMap) keys)
//!     - **StrictFiniteInDebug**: Zero overhead in release, catches bugs during development
//!
//!   - **Layer 3: Validated Wrappers**:
//!     - [`RealValidated<K>`] and [`ComplexValidated<K>`]
//!       are the primary user-facing types.
//!     - These are [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html) wrappers that are guaranteed to hold a value that conforms to the [`NumKernel`] `K` (and to the validation policies therein).
//!     - They use extensive macros to implement high-level traits. The logic is clean: perform a check (if necessary) on the input value,
//!       then call the corresponding `unchecked_*` method from the raw trait, and then perform a check on the output value before returning it.
//!       This ensures safety and correctness.
//!
//!     These wrappers use the [newtype pattern](https://doc.rust-lang.org/rust-by-example/generics/new_types.html) to enforce correctness at the type level. By construction, an instance
//!     of [`RealValidated`] is guaranteed to contain a value that has passed the validation policy, eliminating entire
//!     classes of errors (like `NaN` propagation) in user code.
//!
//!   - **Layer 4: High-Level Abstraction Traits**:
//!     - The [`FpScalar`] trait is the central abstraction, defining a common interface for all scalar types. It uses an associated type sealed type (`Kind`),
//!       to enforce that a scalar is either real or complex, but not both.
//!     - [`RealScalar`] and [`ComplexScalar`] are specialized sub-traits of [`FpScalar`] that serve as markers for real and complex numbers, respectively.
//!     - Generic code in a consumer crate is written against these high-level traits.
//!     - The [`RealValidated`] and [`ComplexValidated`] structs from Layer 3 are the concrete implementors of these traits.
//!
//!     These traits provide the final, safe, and generic public API. Library consumers write their algorithms
//!     against these traits, making their code independent of the specific numerical kernel being used.
//!
//!   This layered approach is powerful, providing both high performance (by using unchecked methods internally) and safety
//!   (through the validated wrappers). The use of generics and traits makes it extensible to new numerical backends (as demonstrated by the rug implementation).
//!
//! - **Multiple Numerical Backends**. At the time of writing, 2 numerical backends can be used:
//!   - the standard (high-performance) numerical backend is the one in which the raw floating point and complex numbers are
//!     described by the Rust's native [`f64`] and [`Complex<f64>`](num::Complex) types, as described by the ANSI/IEEE Std 754-1985;
//!   - an optional (high-precision) numerical backend is available if the library is compiled with the optional flag `--features=rug`,
//!     and uses the arbitrary precision raw types `rug::Float` and `rug::Complex` from the Rust library [`rug`](https://crates.io/crates/rug).
//! - **Comprehensive Mathematical Library**. It includes a wide range of mathematical functions for
//!   trigonometry, logarithms, exponentials, and more, all implemented as traits (e.g., [`functions::Sin`], [`functions::Cos`], [`functions::Sqrt`]) and available on the validated types.
//! - **Numerically Robust Implementations**. The library commits to numerical accuracy:
//!   - Neumaier compensated summation (`NeumaierSum`) for the default [`std::iter::Sum`] implementation to minimize precision loss.
//!   - BLAS/LAPACK-style L2 norm (`algorithms::l2_norm::l2_norm`) with incremental scaling to prevent overflow and underflow.
//! - **Robust Error Handling:** The library defines detailed error types for various numerical operations,
//!   ensuring that invalid inputs and outputs are properly handled and reported.
//!   Errors are categorized into input and output errors, with specific variants for different types of numerical
//!   issues such as division by zero, invalid values, and subnormal numbers.
//! - **Conditional Backtrace Capture:** Backtrace capture in error types is disabled by default for maximum
//!   performance. Enable the `backtrace` feature flag for debugging to get full stack traces in error types.
//! - **Conditional `Copy` Implementation:** Validated types ([`RealValidated`], [`ComplexValidated`]) automatically
//!   implement [`Copy`] when their underlying raw types support it. This enables zero-cost pass-by-value semantics
//!   for native 64-bit types while correctly requiring [`Clone`] for non-[`Copy`] backends like `rug`.
//! - **Constrained Scalar Types:** The [`scalars`] module provides validated wrapper types for common domain-specific
//!   constraints: [`scalars::AbsoluteTolerance`] (non-negative), [`scalars::RelativeTolerance`] (non-negative, with
//!   conversion to absolute), [`scalars::PositiveRealScalar`] (strictly > 0), and [`scalars::NonNegativeRealScalar`]
//!   (≥ 0). All types are generic over any [`RealScalar`] backend.
//! - **Approximate Equality Comparisons:** All validated types implement the [`approx`] crate traits
//!   ([`AbsDiffEq`](approx::AbsDiffEq), [`RelativeEq`](approx::RelativeEq), [`UlpsEq`](approx::UlpsEq))
//!   for tolerance-based floating-point comparisons. This is essential for testing numerical algorithms
//!   and handling floating-point precision limitations. The `approx` crate is re-exported for convenience.
//! - **Comprehensive Documentation:** The library includes detailed documentation for each struct, trait, method,
//!   and error type, making it easy for users to understand and utilize the provided functionality.
//!   Examples are provided for key functions to demonstrate their usage and expected behavior.
//! - **Zero-Copy Conversions:** The native 64-bit validated types ([`RealNative64StrictFinite`], [`RealNative64StrictFiniteInDebug`])
//!   implement [`bytemuck::CheckedBitPattern`](https://docs.rs/bytemuck/latest/bytemuck/checked/trait.CheckedBitPattern.html)
//!   and [`bytemuck::NoUninit`](https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html),
//!   enabling safe, zero-copy conversions between byte representations and validated types. This is particularly useful for
//!   interoperability with binary data formats, serialization, and performance-critical code. The conversion automatically
//!   validates the bit pattern, rejecting invalid values (NaN, Infinity, subnormal numbers) at compile time for type safety.
//!
//! # Architecture Deep Dive
//!
//! For a comprehensive understanding of the library's architecture, design patterns, and implementation details,
//! see the **[Architecture Guide](https://gitlab.com/max.martinelli/num-valid/-/blob/master/docs/ARCHITECTURE.md)**
//! (also available in the repository at `docs/ARCHITECTURE.md`).
//!
//! The guide covers:
//! - **Detailed explanation of the 4-layer design** with examples and rationale
//! - **How to add a new numerical backend** (step-by-step guide with checklist)
//! - **How to implement new mathematical functions** (complete template)
//! - **Error handling architecture** (two-phase error model, backtrace handling)
//! - **Performance considerations** (zero-cost abstractions, optimization patterns)
//! - **Macro system** (code generation patterns and proposals)
//! - **Design patterns reference** (newtype, marker traits, sealed traits, etc.)
//!
//! **For Contributors**: Reading the architecture guide is essential before submitting PRs, as it explains
//! the design philosophy and implementation conventions that keep the codebase consistent and maintainable.
//!
//! # Compiler Requirement: Rust Nightly
//! This library currently requires the **nightly** toolchain because it uses some unstable Rust features which,
//! at the time of writing (January 2026), are not yet available in stable or beta releases. These features are:
//!   - `trait_alias`: For ergonomic trait combinations
//!   - `error_generic_member_access`: For advanced error handling
//!   - `box_patterns`: For ergonomic pattern matching on `Box<T>` in error handling
//!
//! If these features are stabilized in a future Rust release, the library will be updated to support the stable compiler.
//!
//! To use the nightly toolchain, please run:
//!
//! ```bash
//! rustup install nightly
//! rustup override set nightly
//! ```
//!
//! This will set your environment to use the nightly compiler, enabling compatibility with the current version of the
//! library.
//!
//! # Getting Started
//!
//! This guide will walk you through the basics of using [`num-valid`](crate).
//!
//! ## 1. Add [`num-valid`](crate) to your Project
//!
//! Add the following to your `Cargo.toml` (change the versions to the latest ones):
//!
//! ```toml
//! [dependencies]
//! num-valid = "0.3"    # Change to the latest version
//! try_create = "0.1.2" # Needed for the TryNew trait
//! num = "0.4"          # For basic numeric traits
//! ```
//!
//! ## 1.5. Quick Start with Literal Macros (Recommended)
//!
//! The easiest way to create validated numbers is using the [`real!`] and [`complex!`] macros:
//!
//! ```rust
//! use num_valid::{real, complex};
//! use std::f64::consts::PI;
//!
//! // Create validated real numbers from literals
//! let x = real!(3.14159);
//! let angle = real!(PI / 4.0);
//! let radius = real!(5.0);
//!
//! // Create validated complex numbers (real, imaginary)
//! let z1 = complex!(1.0, 2.0);   // 1 + 2i
//! let z2 = complex!(-3.0, 4.0);  // -3 + 4i
//!
//! // Use them in calculations - NaN/Inf propagation impossible!
//! let area = real!(PI) * radius.clone() * radius;  // Type-safe area calculation
//! let product = z1 * z2;                           // Safe complex arithmetic
//! ```
//!
//! **Why use macros?**
//! - **Ergonomic**: Concise syntax similar to Rust's built-in `vec![]`, `format!()`, etc.
//! - **Safe**: Validates at construction time, preventing NaN/Inf from entering your calculations
//! - **Clear panics**: Invalid literals (like `real!(f64::NAN)`) panic immediately with descriptive messages
//! - **Compile-time friendly**: Works with constants and expressions evaluated at compile time
//!
//! For runtime values or when you need error handling, see the manual construction methods below.
//!
//! ### Feature Flags
//!
//! The library provides several optional feature flags:
//!
//! | Feature | Description |
//! |---------|-------------|
//! | `rug` | Enables the high-precision arbitrary arithmetic backend using [`rug`](https://crates.io/crates/rug). See LGPL-3.0 notice below. |
//! | `backtrace` | Enables backtrace capture in error types for debugging. Disabled by default for performance. |
//!
//! Example with multiple features:
//!
//! ```toml
//! [dependencies]
//! num-valid = { version = "0.3", features = ["rug", "backtrace"] }
//! try_create = "0.1.2"
//! num = "0.4"
//! ```
//!
//! ## 2. Core Concept: Validated Types
//!
//! The central idea in [`num-valid`](crate) is to use **validated types** instead of raw primitives like [`f64`].
//! These are wrappers that guarantee their inner value is always valid (e.g., not `NaN` or `Infinity`) according to
//! a specific policy.
//!
//! The most common type you'll use is [`RealNative64StrictFinite`], which wraps an [`f64`] and ensures it's always finite,
//! both in Debug and Release mode. For a similar type wrapping an [`f64`] that ensures it's always finite, but with the
//! validity checks executed only in Debug mode (providing performance equal to the raw [`f64`] type), you can use
//! [`RealNative64StrictFiniteInDebug`].
//!
//! ## 3. Your First Calculation
//!
//! Let's perform a square root calculation. You'll need to bring the necessary traits into scope.
//!
//! ```rust
//! // Import the validated type and necessary traits
//! use num_valid::{
//!     RealNative64StrictFinite,
//!     functions::{Sqrt, SqrtRealInputErrors, SqrtRealErrors},
//! };
//! use try_create::TryNew;
//!
//! // 1. Create a validated number. try_new() returns a Result.
//! let x = RealNative64StrictFinite::try_new(4.0).unwrap();
//!
//! // 2. Use the direct method for operations.
//! // This will panic if the operation is invalid (e.g., sqrt of a negative).
//! let sqrt_x = x.sqrt();
//! assert_eq!(*sqrt_x.as_ref(), 2.0);
//!
//! // 3. Use the `try_*` methods for error handling.
//! // This is the safe way to handle inputs that might be out of the function's domain.
//! let neg_x = RealNative64StrictFinite::try_new(-4.0).unwrap();
//! let sqrt_neg_x_result = neg_x.try_sqrt();
//!
//! // The operation fails gracefully, returning an Err.
//! assert!(sqrt_neg_x_result.is_err());
//!
//! // The error gives information about the problem that occurred
//! if let Err(SqrtRealErrors::Input { source }) = sqrt_neg_x_result {
//!     assert!(matches!(source, SqrtRealInputErrors::NegativeValue { .. }));
//! }
//! ```
//!
//! ## 4. Writing Generic Functions
//!
//! The real power of [`num-valid`](crate) comes from writing generic functions that work with any
//! supported numerical type. You can do this by using the [`FpScalar`] and [`RealScalar`] traits as bounds.
//!
//! ```rust
//! use num_valid::{
//!     RealScalar, RealNative64StrictFinite, FpScalar,
//!     functions::{Abs, Sin, Cos},
//! };
//! use num::One;
//! use try_create::TryNew;
//!
//! // This function works for any type that implements RealScalar,
//! // including f64, RealNative64StrictFinite, and RealRugStrictFinite.
//! fn verify_trig_identity<T: RealScalar>(angle: T) -> T {
//!     // We can use .sin(), .cos(), and arithmetic ops because they are
//!     // required by the RealScalar trait.
//!     let sin_x = angle.clone().sin();
//!     let cos_x = angle.cos();
//!     (sin_x.clone() * sin_x) + (cos_x.clone() * cos_x)
//! }
//!
//! // Define a type alias for convenience
//! type MyReal = RealNative64StrictFinite;
//!
//! // Call it with a validated f64 type.
//! let angle = MyReal::try_from_f64(0.5).unwrap();
//! let identity = verify_trig_identity(angle);
//!
//! // The result should be very close to 1.0.
//! let one = MyReal::one();
//! assert!((identity - one).abs() < MyReal::try_from_f64(1e-15).unwrap());
//! ```
//!
//! If the `rug` feature is enabled, you could call the exact same
//! function with a high-precision number changing only the definition
//! of the alias type `MyReal`. For example, for real numbers with precision of 100 bits:
//! ```rust
//! # #[cfg(feature = "rug")] {
//! // Import the rug-based types
//! use num_valid::{
//!     RealScalar, RealRugStrictFinite, FpScalar,
//!     functions::{Abs, Sin, Cos},
//! };
//! use num::One;
//! use try_create::TryNew;
//!
//! // This function works for any type that implements RealScalar,
//! // including f64, RealNative64StrictFinite, and RealRugStrictFinite.
//! fn verify_trig_identity<T: RealScalar>(angle: T) -> T {
//!     // We can use .sin(), .cos(), and arithmetic ops because they are
//!     // required by the RealScalar trait.
//!     let sin_x = angle.clone().sin();
//!     let cos_x = angle.cos();
//!     (sin_x.clone() * sin_x) + (cos_x.clone() * cos_x)
//! }
//!
//! // Define a type alias for convenience - real number with precision of 100 bits
//! type MyReal = RealRugStrictFinite<100>;
//!
//! // Initialize it with an f64 value.
//! let angle = MyReal::try_from_f64(0.5).unwrap();
//! let identity = verify_trig_identity(angle);
//!
//! // The result should be very close to 1.0.
//! let one = MyReal::one();
//! assert!((identity - one).abs() < MyReal::try_from_f64(1e-15).unwrap());
//! # }
//! ```
//!
//! ## 5. Working with Complex Numbers
//!
//! The library also provides validated complex number types:
//!
//! ```rust
//! use num_valid::{ComplexNative64StrictFinite, functions::Abs};
//! use num::Complex;
//! use try_create::TryNew;
//!
//! // Create a validated complex number
//! let z = ComplexNative64StrictFinite::try_new(Complex::new(3.0, 4.0)).unwrap();
//!
//! // Complex operations work the same way
//! let magnitude = z.abs();
//! assert_eq!(*magnitude.as_ref(), 5.0); // |3 + 4i| = 5
//! ```
//!
//! ## 6. Zero-Copy Conversions with Bytemuck
//!
//! For performance-critical applications working with binary data, the library provides safe, zero-copy
//! conversions through the [`bytemuck`](https://docs.rs/bytemuck) crate. The native 64-bit validated types
//! ([`RealNative64StrictFinite`], [`RealNative64StrictFiniteInDebug`]) implement
//! [`CheckedBitPattern`](https://docs.rs/bytemuck/latest/bytemuck/checked/trait.CheckedBitPattern.html)
//! and [`NoUninit`](https://docs.rs/bytemuck/latest/bytemuck/trait.NoUninit.html), enabling safe conversions
//! that automatically validate bit patterns:
//!
//! ```rust
//! use num_valid::RealNative64StrictFinite;
//! use bytemuck::checked::try_from_bytes;
//!
//! // Convert from bytes - validation happens automatically
//! let value = 42.0_f64;
//! let bytes = value.to_ne_bytes();
//! let validated: &RealNative64StrictFinite = try_from_bytes(&bytes).unwrap();
//! assert_eq!(*validated.as_ref(), 42.0);
//!
//! // Invalid values (NaN, Infinity, subnormals) are rejected
//! let nan_bytes = f64::NAN.to_ne_bytes();
//! assert!(try_from_bytes::<RealNative64StrictFinite>(&nan_bytes).is_err());
//! ```
//!
//! This is particularly useful for:
//! - Loading validated numbers from binary file formats
//! - Interoperability with serialization libraries
//! - Processing validated numerical data in performance-critical loops
//! - Working with memory-mapped files containing numerical data
//!
//! For comprehensive examples including slice operations and error handling, see the test module
//! in the [`backends::native64::validated`] module source code.
//!
//! ## 7. Validated Tolerances and Constrained Scalars
//!
//! The [`scalars`] module provides validated wrapper types for common domain-specific constraints:
//!
//! ```rust
//! use num_valid::{RealNative64StrictFinite, RealScalar};
//! use num_valid::scalars::{
//!     AbsoluteTolerance, RelativeTolerance,
//!     PositiveRealScalar, NonNegativeRealScalar
//! };
//! use try_create::TryNew;
//!
//! // AbsoluteTolerance: Non-negative tolerance (≥ 0)
//! let abs_tol = AbsoluteTolerance::try_new(
//!     RealNative64StrictFinite::from_f64(1e-10)
//! )?;
//!
//! // RelativeTolerance: Non-negative, with conversion to absolute tolerance
//! let rel_tol = RelativeTolerance::try_new(
//!     RealNative64StrictFinite::from_f64(1e-6)
//! )?;
//! let reference = RealNative64StrictFinite::from_f64(1000.0);
//! let abs_from_rel = rel_tol.absolute_tolerance(reference); // = 1e-3
//!
//! // PositiveRealScalar: Strictly positive (> 0), rejects zero
//! let step_size = PositiveRealScalar::try_new(
//!     RealNative64StrictFinite::from_f64(0.001)
//! )?;
//! // PositiveRealScalar::try_new(zero) would return an error!
//!
//! // NonNegativeRealScalar: Non-negative (≥ 0), accepts zero
//! let threshold = NonNegativeRealScalar::try_new(
//!     RealNative64StrictFinite::from_f64(0.0)
//! )?;  // OK!
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! **Key differences:**
//! - [`scalars::PositiveRealScalar`]: Rejects zero (useful for divisors, step sizes)
//! - [`scalars::NonNegativeRealScalar`]: Accepts zero (useful for thresholds, counts)
//! - All types are generic over any [`RealScalar`] backend
//!
//! # Common Pitfalls
//!
//! Here are common mistakes to avoid when using [`num-valid`](crate):
//!
//! ## 1. Forgetting `Clone` for Reused Values
//!
//! Validated types consume `self` in mathematical operations. Clone before reuse:
//!
//! ```rust
//! use num_valid::{real, functions::{Sin, Cos}};
//! let x = real!(1.0);
//!
//! // ❌ Wrong - x is moved after first use:
//! // let sin_x = x.sin();
//! // let cos_x = x.cos(); // Error: x already moved!
//!
//! // ✅ Correct - clone before move:
//! let sin_x = x.clone().sin();
//! let cos_x = x.cos();
//! ```
//!
//! ## 2. Using `from_f64` with Untrusted Input
//!
//! [`RealScalar::from_f64`] panics on invalid input. Use [`RealScalar::try_from_f64`] for user data:
//!
//! ```rust
//! use num_valid::{RealNative64StrictFinite, RealScalar};
//!
//! fn process_user_input(user_input: f64) -> Result<(), Box<dyn std::error::Error>> {
//!     // ❌ Dangerous - panics on NaN/Inf:
//!     // let x = RealNative64StrictFinite::from_f64(user_input);
//!
//!     // ✅ Safe - handles errors gracefully:
//!     let x = RealNative64StrictFinite::try_from_f64(user_input)?;
//!     println!("Validated: {}", x);
//!     Ok(())
//! }
//! # process_user_input(42.0).unwrap();
//! ```
//!
//! ## 3. Validation Policy Mismatch
//!
//! Choose the right policy for your use case:
//!
//! | Policy | Debug Build | Release Build | Use Case |
//! |--------|-------------|---------------|----------|
//! | `StrictFinite` | ✅ Validates | ✅ Validates | Safety-critical code |
//! | `StrictFiniteInDebug` | ✅ Validates | ❌ No validation | Performance-critical code |
//!
//! ```rust
//! use num_valid::{RealNative64StrictFinite, RealNative64StrictFiniteInDebug};
//!
//! // For safety-critical code (always validated)
//! type SafeReal = RealNative64StrictFinite;
//!
//! // For performance-critical code (validated only in debug builds)
//! type FastReal = RealNative64StrictFiniteInDebug;
//! ```
//!
//! ## 4. Ignoring `#[must_use]` Warnings
//!
//! All `try_*` methods return [`Result`]. Don't ignore them:
//!
//! ```rust
//! use num_valid::{RealNative64StrictFinite, functions::Sqrt};
//! use try_create::TryNew;
//!
//! let x = RealNative64StrictFinite::try_new(4.0).unwrap();
//!
//! // ❌ Compiler warning: unused Result
//! // x.try_sqrt();
//!
//! // ✅ Handle the result
//! let sqrt_x = x.try_sqrt()?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # License
//! Copyright 2023-2025, C.N.R. - Consiglio Nazionale delle Ricerche
//!
//! Licensed under either of
//! - Apache License, Version 2.0
//! - MIT license
//!
//! at your option.
//!
//! Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you,
//! as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
//!
//! ## License Notice for Optional Feature Dependencies (LGPL-3.0 Compliance)
//! If you enable the `rug` feature, this project will depend on the [`rug`](https://crates.io/crates/rug) library,
//! which is licensed under the LGPL-3.0 license. Activating this feature may introduce LGPL-3.0 requirements to your
//! project. Please review the terms of the LGPL-3.0 license to ensure compliance.

pub mod algorithms;
pub mod backends;
pub mod core;
pub mod functions;
pub mod kernels;
pub mod prelude;
pub mod scalars;

mod macros;
// Macros are exported at crate root via #[macro_export]

use crate::{
    algorithms::neumaier_sum::NeumaierAddable,
    core::{
        errors::{ErrorsRawRealToInteger, ErrorsTryFromf64},
        traits::{NumKernel, validation::FpChecks},
    },
    functions::{
        ACos, ACosH, ASin, ASinH, ATan, ATan2, ATanH, Abs, Arg, Arithmetic, Clamp, Classify,
        ComplexScalarConstructors, ComplexScalarGetParts, ComplexScalarMutateParts,
        ComplexScalarSetParts, Conjugate, Cos, CosH, Exp, ExpM1, HyperbolicFunctions, Hypot, Ln,
        Ln1p, Log2, Log10, LogarithmFunctions, Max, Min, MulAddRef, Pow,
        PowComplexBaseRealExponentErrors, PowIntExponent, PowRealBaseRealExponentErrors,
        Reciprocal, Rounding, Sign, Sin, SinH, Sqrt, Tan, TanH, TotalCmp, TrigonometricFunctions,
    },
    kernels::{ComplexValidated, RawRealTrait, RawScalarTrait, RealValidated},
};
use num::{Complex, One, Zero};
use rand::{Rng, distr::Distribution};
use serde::{Deserialize, Serialize};
use std::{
    fmt::{Debug, Display},
    ops::{Mul, MulAssign, Neg},
};
use try_create::IntoInner;

pub use crate::backends::native64::validated::{
    ComplexNative64StrictFinite, ComplexNative64StrictFiniteInDebug, Native64StrictFinite,
    Native64StrictFiniteInDebug, RealNative64StrictFinite, RealNative64StrictFiniteInDebug,
};

#[cfg(feature = "rug")]
pub use crate::backends::rug::validated::{
    ComplexRugStrictFinite, RealRugStrictFinite, RugStrictFinite,
};

/// Re-export the `approx` crate for convenient access to approximate comparison traits.
///
/// This allows users to use `num_valid::approx` instead of adding `approx` as a separate dependency.
/// The validated types [`RealValidated`] and [`ComplexValidated`] implement the following traits:
/// - [`AbsDiffEq`](approx::AbsDiffEq): Absolute difference equality
/// - [`RelativeEq`](approx::RelativeEq): Relative difference equality  
/// - [`UlpsEq`](approx::UlpsEq): Units in Last Place equality
///
/// # Example
///
/// ```rust
/// use num_valid::{RealNative64StrictFinite, RealScalar};
/// use num_valid::scalars::AbsoluteTolerance;
/// use num_valid::approx::assert_abs_diff_eq;
/// use try_create::TryNew;
///
/// let a = RealNative64StrictFinite::from_f64(1.0);
/// let b = RealNative64StrictFinite::from_f64(1.0 + 1e-10);
/// let eps = AbsoluteTolerance::try_new(RealNative64StrictFinite::from_f64(1e-9)).unwrap();
/// assert_abs_diff_eq!(a, b, epsilon = eps);
/// ```
pub use approx;

//------------------------------------------------------------------------------------------------
/// Private module to encapsulate implementation details of the scalar kind for mutual exclusion.
///
/// This module provides the sealed trait pattern to ensure that scalar types can only be
/// either real or complex, but never both. The sealed nature prevents external crates
/// from implementing the trait, maintaining the library's type safety guarantees.
pub(crate) mod scalar_kind {
    /// A sealed trait to mark the "kind" of a scalar.
    ///
    /// External users cannot implement this trait due to the sealed pattern.
    /// This ensures that only the library-defined scalar kinds (Real and Complex)
    /// can be used with the [`FpScalar`](super::FpScalar) trait.
    pub trait Sealed {}

    /// A marker type for real scalar types.
    ///
    /// This type is used as the `Kind` associated type for real number types
    /// in the [`FpScalar`](super::FpScalar) trait, ensuring type-level distinction
    /// between real and complex scalars.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct Real;
    impl Sealed for Real {}

    /// A marker type for complex scalar types.
    ///
    /// This type is used as the `Kind` associated type for complex number types
    /// in the [`FpScalar`](super::FpScalar) trait, ensuring type-level distinction
    /// between real and complex scalars.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub struct Complex;
    impl Sealed for Complex {}
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------

/// Fundamental trait alias bundling core requirements for all scalar types.
///
/// [`ScalarCore`] aggregates the essential traits that every scalar type in [`num-valid`](crate)
/// must implement, regardless of whether it's real or complex, native or arbitrary-precision.
/// This trait alias provides a single, maintainable definition of the foundational capabilities
/// required by all floating-point scalar types.
///
/// ## Included Traits
///
/// - **[`Sized`]**: Types must have a known size at compile time
/// - **[`Clone`]**: Values can be duplicated (note: not necessarily [`Copy`])
/// - **[`Debug`]**: Supports formatted debugging output with `{:?}`
/// - **[`Display`]**: Supports user-facing formatted output with `{}`
/// - **[`PartialEq`]**: Supports equality comparisons (may upgrade to [`Eq`] with finite guarantees)
/// - **[`Send`]**: Safe to transfer ownership across thread boundaries
/// - **[`Sync`]**: Safe to share references across threads
/// - **[`Serialize`]**: Can be serialized (via [`serde`])
/// - **[`Deserialize`]**: Can be deserialized (via [`serde`])
/// - **`'static`**: Contains no non-static references
///
/// ## Design Rationale
///
/// This trait alias serves several important purposes:
///
/// 1. **Single Source of Truth**: Defines core requirements in one place, reducing duplication
/// 2. **Maintainability**: Changes to fundamental requirements only need to be made once
/// 3. **Readability**: Simplifies trait bounds in [`FpScalar`] and other high-level traits
/// 4. **Consistency**: Ensures all scalar types share the same baseline capabilities
///
/// ## Usage in Type Bounds
///
/// [`ScalarCore`] is primarily used as a super-trait bound in [`FpScalar`]:
///
/// ```rust
/// # use num_valid::ScalarCore;
/// // Instead of listing all traits individually:
/// // pub trait FpScalar: Sized + Clone + Debug + Display + PartialEq + Send + Sync + ...
///
/// // We use the trait alias:
/// pub trait FpScalar: ScalarCore + /* other mathematical traits */ {
///     // ...
/// }
/// ```
///
/// ## Thread Safety
///
/// The inclusion of [`Send`] and [`Sync`] makes all scalar types safe for concurrent use:
/// - **[`Send`]**: Scalars can be moved between threads
/// - **[`Sync`]**: Scalars can be shared via `&T` between threads
///
/// This enables parallel numerical computations without additional synchronization overhead.
///
/// ## Serialization Support
///
/// All scalar types support serialization through [`serde`]:
///
/// ```rust,ignore
/// use num_valid::RealNative64StrictFinite;
/// use try_create::TryNew;
/// use serde_json;
///
/// let value = RealNative64StrictFinite::try_new(3.14159).unwrap();
///
/// // Serialize to JSON
/// let json = serde_json::to_string(&value).unwrap();
/// assert_eq!(json, "3.14159");
///
/// // Deserialize from JSON
/// let deserialized: RealNative64StrictFinite = serde_json::from_str(&json).unwrap();
/// assert_eq!(value, deserialized);
/// ```
///
/// ## Relationship to Other Traits
///
/// - **[`FpScalar`]**: Extends [`ScalarCore`] with mathematical operations and floating-point checks
/// - **[`RealScalar`]**: Further specializes [`FpScalar`] for real numbers
/// - **[`ComplexScalar`]**: Further specializes [`FpScalar`] for complex numbers
///
/// ## Implementation Note
///
/// This is a **trait alias**, not a regular trait. It cannot be implemented directly;
/// instead, types must implement all the constituent traits individually. The trait alias
/// simply provides a convenient shorthand for referring to this specific combination of traits.
///
/// ## See Also
///
/// - [`FpScalar`]: The main scalar trait that uses [`ScalarCore`] as a foundation
/// - [`RealScalar`]: Specialized trait for real number types
/// - [`ComplexScalar`]: Specialized trait for complex number types
pub trait ScalarCore = Sized
    + Clone
    + Debug
    + Display
    + PartialEq
    + Send
    + Sync
    + Serialize
    + for<'a> Deserialize<'a>
    + 'static;

/// # Core trait for a floating-point scalar number (real or complex)
///
/// [`FpScalar`] is a fundamental trait in [`num-valid`](crate) that provides a common interface
/// for all floating-point scalar types, whether they are real or complex, and regardless
/// of their underlying numerical kernel (e.g., native [`f64`] or arbitrary-precision [`rug`](https://docs.rs/rug/latest/rug/index.html) types).
///
/// This trait serves as a primary bound for generic functions and structures that need to
/// operate on scalar values capable of floating-point arithmetic. It aggregates a large
/// number of mathematical function traits (e.g., [`functions::Sin`], [`functions::Cos`], [`functions::Exp`], [`functions::Sqrt`]) and
/// core properties.
///
/// ## Key Responsibilities and Associated Types:
///
/// - **Scalar Kind (`FpScalar::Kind`):**
///   This associated type specifies the fundamental nature of the scalar, which can be
///   either `scalar_kind::Real` or `scalar_kind::Complex`. It is bound by the private,
///   sealed trait `scalar_kind::Sealed`. This design enforces **mutual exclusion**:
///   since a type can only implement [`FpScalar`] once, it can only have one `Kind`,
///   making it impossible for a type to be both a `RealScalar` and a `ComplexScalar` simultaneously.
///
/// - **Real Type Component ([`FpScalar::RealType`]):**
///   Specifies the real number type corresponding to this scalar via [`RealType`](FpScalar::RealType).
///   - For real scalars (e.g., [`f64`], [`RealNative64StrictFinite`], [`RealNative64StrictFiniteInDebug`],
///     `RealRugStrictFinite`, etc.), [`FpScalar::RealType`] is `Self`.
///   - For complex scalars (e.g., [`Complex<f64>`](num::Complex), [`ComplexNative64StrictFinite`], [`ComplexNative64StrictFiniteInDebug`],
///     `ComplexRugStrictFinite`, etc.), [`FpScalar::RealType`] is their underlying real component type
///     (e.g., [`f64`], [`RealNative64StrictFinite`], [`RealNative64StrictFiniteInDebug`], `RealRugStrictFinite`, etc.).
///  
///   Crucially, this [`FpScalar::RealType`] is constrained to implement [`RealScalar`], ensuring consistency.
///
/// - **Core Floating-Point Properties:**
///   [`FpScalar`] requires implementations of the trait [`FpChecks`], which provides fundamental floating-point checks:
///   - [`is_finite()`](FpChecks::is_finite): Checks if the number is finite.
///   - [`is_infinite()`](FpChecks::is_infinite): Checks if the number is positive or negative infinity.
///   - [`is_nan()`](FpChecks::is_nan): Checks if the number is "Not a Number".
///   - [`is_normal()`](FpChecks::is_normal): Checks if the number is a normal (not zero, subnormal, infinite, or NaN).
///
/// ## Trait Bounds:
///
/// [`FpScalar`] itself has several important trait bounds:
/// - `Sized + Clone + Debug + Display + PartialEq`: Standard utility traits. Note that scalar
///   types are [`Clone`] but not necessarily [`Copy`].
/// - [`Zero`] + [`One`]: From `num_traits`, ensuring the type has additive and multiplicative identities.
/// - [`Neg<Output = Self>`](Neg): Ensures the type can be negated.
/// - [`Arithmetic`]: A custom aggregate trait in [`num-valid`](crate) that bundles standard
///   arithmetic operator traits (like [`Add`](std::ops::Add), [`Sub`](std::ops::Sub), [`Mul`], [`Div`](std::ops::Div)).
/// - [`RandomSampleFromF64`]: Allows the type to be randomly generated from any distribution
///   that produces `f64`, integrating with the [`rand`] crate.
/// - `Send + Sync + 'static`: Makes the scalar types suitable for use in concurrent contexts.
/// - A comprehensive suite of mathematical function traits like [`functions::Sin`], [`functions::Cos`], [`functions::Exp`], [`functions::Ln`], [`functions::Sqrt`], etc.
///
/// ## Relationship to Other Traits:
///
/// - [`RealScalar`]: A sub-trait of [`FpScalar`] for real numbers, defined by the constraint `FpScalar<Kind = scalar_kind::Real>`.
/// - [`ComplexScalar`]: A sub-trait of [`FpScalar`] for complex numbers, defined by the constraint `FpScalar<Kind = scalar_kind::Complex>`.
/// - [`NumKernel`]: Policies like [`Native64StrictFinite`]
///   are used to validate the raw values that are wrapped inside types implementing `FpScalar`.
///
/// ## Example: Generic Function
///
/// Here is how you can write a generic function that works with any scalar type
/// implementing `FpScalar`.
///
/// ```rust
/// use num_valid::{FpScalar, functions::{MulAddRef, Sqrt}, RealNative64StrictFinite};
/// use num::Zero;
/// use try_create::TryNew;
///
/// // This function works with any FpScalar type.
/// fn norm_and_sqrt<T: FpScalar>(a: T, b: T) -> T {
///     let val = a.clone().mul_add_ref(&a, &(b.clone() * b)); // a*a + b*b
///     val.sqrt()
/// }
///
/// // Also this function works with any FpScalar type.
/// fn multiply_if_not_zero<T: FpScalar>(a: T, b: T) -> T {
///     if !a.is_zero() && !b.is_zero() {
///         a * b
///     } else {
///         T::zero()
///     }
/// }
///
/// // Example usage
/// let a = RealNative64StrictFinite::try_new(3.0).unwrap();
/// let b = RealNative64StrictFinite::try_new(4.0).unwrap();
/// let result = norm_and_sqrt(a, b);
/// assert_eq!(*result.as_ref(), 5.0);
/// ```
pub trait FpScalar:
    ScalarCore
    + Zero
    + One
    + IntoInner<InnerType: RawScalarTrait>
    + Arithmetic
    + Abs<Output = Self::RealType>
    + Sqrt
    + PowIntExponent<RawType = Self::InnerType>
    + TrigonometricFunctions
    + HyperbolicFunctions
    + LogarithmFunctions
    + Exp
    + FpChecks
    + Neg<Output = Self>
    + MulAddRef
    + Reciprocal
    + NeumaierAddable
    + RandomSampleFromF64
{
    /// The kind of scalar this is, e.g., `Real` or `Complex`.
    /// This is a sealed trait to prevent external implementations.
    type Kind: scalar_kind::Sealed;

    /// The real number type corresponding to this scalar.
    ///
    /// - For real scalars (e.g., `f64`), `RealType` is `Self`.
    /// - For complex scalars (e.g., `Complex<f64>`), `RealType` is their underlying
    ///   real component type (e.g., `f64`).
    ///
    /// This `RealType` is guaranteed to implement [`RealScalar`] and belong to the
    /// same numerical kernel as `Self`.
    type RealType: RealScalar<RealType = Self::RealType>;

    /// Returns a reference to the underlying raw scalar value.
    fn as_raw_ref(&self) -> &Self::InnerType;
}
//-------------------------------------------------------------------------------------------------------------

//-------------------------------------------------------------------------------------------------------------

/// Provides fundamental mathematical constants for floating-point scalar types.
///
/// This trait defines methods to obtain commonly used mathematical constants
/// in the appropriate precision and type for the implementing scalar type.
/// All constants are guaranteed to be finite and valid according to the
/// scalar's validation policy.
///
/// ## Design Principles
///
/// - **Type-Appropriate Precision**: Constants are provided at the precision
///   of the implementing type (e.g., `f64` precision for native types,
///   arbitrary precision for `rug` types).
/// - **Validation Compliance**: All returned constants are guaranteed to pass
///   the validation policy of the implementing type.
/// - **Mathematical Accuracy**: Constants use the most accurate representation
///   available for the underlying numerical type.
///
/// ## Usage Examples
///
/// ```rust
/// use num_valid::{RealNative64StrictFinite, Constants, functions::Exp};
/// use try_create::TryNew;
///
/// // Get mathematical constants
/// let pi = RealNative64StrictFinite::pi();
/// let e = RealNative64StrictFinite::e();
/// let eps = RealNative64StrictFinite::epsilon();
///
/// // Use in calculations
/// let circle_area = pi.clone() * &(pi * RealNative64StrictFinite::two());
/// let exp_1 = e.exp(); // e^e
/// ```
///
/// ## Backend-Specific Behavior
///
/// ### Native `f64` Backend
/// - Uses standard library constants like `std::f64::consts::PI`
/// - IEEE 754 double precision (53-bit significand)
/// - Hardware-optimized representations
///
/// ### Arbitrary-Precision (`rug`) Backend
/// - Constants computed at compile-time specified precision
/// - Exact representations within precision limits
/// - May use higher-precision intermediate calculations
pub trait Constants: Sized {
    /// [Machine epsilon] value for `Self`.
    ///
    /// This is the difference between `1.0` and the next larger representable number.
    /// It represents the relative precision of the floating-point format.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use num_valid::{RealNative64StrictFinite, Constants};
    ///
    /// let eps = RealNative64StrictFinite::epsilon();
    /// // For f64, this is approximately 2.220446049250313e-16
    /// ```
    ///
    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
    fn epsilon() -> Self;

    /// Build and return the (floating point) value -1. represented by the proper type.
    fn negative_one() -> Self;

    /// Build and return the (floating point) value 0.5 represented by the proper type.
    fn one_div_2() -> Self;

    /// Build and return the (floating point) value `π` represented by the proper type.
    fn pi() -> Self;

    /// Build and return the (floating point) value `2 π` represented by the proper type.
    fn two_pi() -> Self;

    /// Build and return the (floating point) value `π/2` represented by the proper type.
    fn pi_div_2() -> Self;

    /// Build and return the (floating point) value 2. represented by the proper type.
    fn two() -> Self;

    /// Build and return the maximum finite value allowed by the current floating point representation.
    fn max_finite() -> Self;

    /// Build and return the minimum finite (i.e., the most negative) value allowed by the current floating point representation.
    fn min_finite() -> Self;

    /// Build and return the natural logarithm of 2, i.e. the (floating point) value `ln(2)`, represented by the proper type.
    fn ln_2() -> Self;

    /// Build and return the natural logarithm of 10, i.e. the (floating point) value `ln(10)`, represented by the proper type.
    fn ln_10() -> Self;

    /// Build and return the base-10 logarithm of 2, i.e. the (floating point) value `Log_10(2)`, represented by the proper type.
    fn log10_2() -> Self;

    /// Build and return the base-2 logarithm of 10, i.e. the (floating point) value `Log_2(10)`, represented by the proper type.
    fn log2_10() -> Self;

    /// Build and return the base-2 logarithm of `e`, i.e. the (floating point) value `Log_2(e)`, represented by the proper type.
    fn log2_e() -> Self;

    /// Build and return the base-10 logarithm of `e`, i.e. the (floating point) value `Log_10(e)`, represented by the proper type.
    fn log10_e() -> Self;

    /// Build and return the (floating point) value `e` represented by the proper type.
    fn e() -> Self;
}

/// # Trait for scalar real numbers
///
/// [`RealScalar`] extends the fundamental [`FpScalar`] trait, providing an interface
/// specifically for real (non-complex) floating-point numbers. It introduces
/// operations and properties that are unique to real numbers, such as ordering,
/// rounding, and clamping.
///
/// This trait is implemented by real scalar types within each numerical kernel,
/// for example, [`f64`] for the native kernel,
/// and `RealRugStrictFinite` for the `rug` kernel (when the `rug` feature is enabled).
///
/// ## Key Design Principles
///
/// - **Inheritance from [`FpScalar`]:** As a sub-trait of [`FpScalar`], any `RealScalar`
///   type automatically gains all the capabilities of a general floating-point number,
///   including basic arithmetic and standard mathematical functions (e.g., `sin`, `exp`, `sqrt`).
/// - **Raw Underlying Type ([`RawReal`](Self::RawReal)):**
///   This associated type specifies the most fundamental, "raw" representation of the real number,
///   which implements the [`RawRealTrait`]. This is the type used for low-level, unchecked
///   operations within the library's internal implementation.
///   - For [`f64`], [`RealNative64StrictFinite`] and [`RealNative64StrictFiniteInDebug`], `RawReal` is [`f64`].
///   - For `RealRugStrictFinite<P>`, `RawReal` is [`rug::Float`](https://docs.rs/rug/latest/rug/struct.Float.html).
/// - **Reference-Based Operations**: Many operations take arguments by reference (`&Self`)
///   to avoid unnecessary clones of potentially expensive arbitrary-precision numbers.
/// - **Fallible Constructors**: [`try_from_f64()`](Self::try_from_f64) validates inputs
///   and ensures exact representability for arbitrary-precision types.
///
/// ## Creating Validated Real Numbers
///
/// There are multiple ways to create validated real scalar instances, depending on your
/// source data and use case:
///
/// ### 1. From f64 Values (Most Common)
///
/// Use [`try_from_f64()`](Self::try_from_f64) for fallible conversion with error handling,
/// or [`from_f64()`](Self::from_f64) for infallible conversion that panics on invalid input:
///
/// ```rust
/// use num_valid::{RealNative64StrictFinite, RealScalar};
///
/// // Fallible conversion (recommended for runtime values)
/// let x = RealNative64StrictFinite::try_from_f64(3.14)?;
/// assert_eq!(x.as_ref(), &3.14);
///
/// // Panicking conversion (safe for known-valid constants)
/// let pi = RealNative64StrictFinite::from_f64(std::f64::consts::PI);
/// let e = RealNative64StrictFinite::from_f64(std::f64::consts::E);
///
/// // For convenience with literals, consider using the real!() macro:
/// use num_valid::real;
/// let quick = real!(3.14);  // Equivalent to from_f64(3.14)
///
/// // Error handling for invalid values
/// let invalid = RealNative64StrictFinite::try_from_f64(f64::NAN);
/// assert!(invalid.is_err()); // NaN is rejected
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ### 2. From Raw Values (Advanced)
///
/// Use [`try_new()`](try_create::TryNew::try_new) when working with the raw underlying type directly:
///
/// ```rust
/// use num_valid::RealNative64StrictFinite;
/// use try_create::TryNew;
///
/// // For native f64 types
/// let x = RealNative64StrictFinite::try_new(42.0)?;
///
/// // For arbitrary-precision types (with rug feature)
/// # #[cfg(feature = "rug")] {
/// use num_valid::RealRugStrictFinite;
/// let high_precision = RealRugStrictFinite::<200>::try_new(
///     rug::Float::with_val(200, 1.5)
/// )?;
/// # }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ### 3. Using Constants
///
/// Leverage the [`Constants`] trait for mathematical constants:
///
/// ```rust
/// use num_valid::{RealNative64StrictFinite, Constants};
///
/// let pi = RealNative64StrictFinite::pi();
/// let e = RealNative64StrictFinite::e();
/// let two = RealNative64StrictFinite::two();
/// let epsilon = RealNative64StrictFinite::epsilon();
/// ```
///
/// ### 4. From Arithmetic Operations
///
/// Create values through validated arithmetic on existing validated numbers:
///
/// ```rust
/// use num_valid::RealNative64StrictFinite;
/// use try_create::TryNew;
///
/// let a = RealNative64StrictFinite::try_new(2.0)?;
/// let b = RealNative64StrictFinite::try_new(3.0)?;
///
/// let sum = a.clone() + b.clone(); // Automatically validated
/// let product = &a * &b;           // Also works with references
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ### 5. Using Zero and One Traits
///
/// For generic code, use [`num::Zero`] and [`num::One`]:
///
/// ```rust
/// use num_valid::RealNative64StrictFinite;
/// use num::{Zero, One};
///
/// let zero = RealNative64StrictFinite::zero();
/// let one = RealNative64StrictFinite::one();
/// assert_eq!(*zero.as_ref(), 0.0);
/// assert_eq!(*one.as_ref(), 1.0);
/// ```
///
/// ### Choosing the Right Method
///
/// | Method | Use When | Panics? | Example |
/// |--------|----------|---------|---------|
/// | `from_f64()` | Value is guaranteed valid (constants) | Yes | `from_f64(PI)` |
/// | `try_from_f64()` | Value might be invalid (user input) | No | `try_from_f64(x)?` |
/// | `try_new()` | Working with raw backend types | No | `try_new(raw_val)?` |
/// | Constants trait | Need mathematical constants | No | `pi()`, `e()` |
/// | Arithmetic | Deriving from other validated values | No | `a + b` |
///
/// ## Type Safety with Validated Types
///
/// Real scalars that use validation policies implementing finite value guarantees
/// automatically gain:
/// - **Full Equality ([`Eq`])**: Well-defined, symmetric equality comparisons
/// - **Hashing ([`Hash`])**: Use as keys in [`HashMap`](std::collections::HashMap) and [`HashSet`](std::collections::HashSet)
/// - **No Total Ordering**: The library intentionally avoids [`Ord`] in favor of
///   more efficient reference-based [`functions::Max`]/[`functions::Min`] operations
///
/// ## Mathematical Operations
///
/// ### Core Arithmetic
/// All standard arithmetic operations are available through the [`Arithmetic`] trait,
/// supporting both value and reference semantics:
/// ```rust
/// use num_valid::RealNative64StrictFinite;
/// use try_create::TryNew;
///
/// let a = RealNative64StrictFinite::try_new(2.0).unwrap();
/// let b = RealNative64StrictFinite::try_new(3.0).unwrap();
///
/// // All combinations supported: T op T, T op &T, &T op T, &T op &T
/// let sum1 = a.clone() + b.clone();
/// let sum2 = &a + &b;
/// let sum3 = a.clone() + &b;
/// let sum4 = &a + b.clone();
///
/// assert_eq!(sum1, sum2);
/// assert_eq!(sum2, sum3);
/// assert_eq!(sum3, sum4);
/// ```
///
/// ### Advanced Functions
///
/// In addition to the functions from [`FpScalar`], `RealScalar` provides a suite of methods common in real number arithmetic.
/// Methods prefixed with `kernel_` provide direct access to underlying mathematical operations with minimal overhead:
///
/// - **Rounding ([`Rounding`]):**
///   [`kernel_ceil()`](Rounding::kernel_ceil), [`kernel_floor()`](Rounding::kernel_floor),
///   [`kernel_round()`](Rounding::kernel_round), [`kernel_round_ties_even()`](Rounding::kernel_round_ties_even),
///   [`kernel_trunc()`](Rounding::kernel_trunc), and [`kernel_fract()`](Rounding::kernel_fract).
///
/// - **Sign Manipulation ([`Sign`]):**
///   [`kernel_copysign()`](Sign::kernel_copysign), [`kernel_signum()`](Sign::kernel_signum),
///   [`kernel_is_sign_positive()`](Sign::kernel_is_sign_positive), and [`kernel_is_sign_negative()`](Sign::kernel_is_sign_negative).
///
/// - **Comparison and Ordering:**
///   - From [`functions::Max`]/[`functions::Min`]: [`max_by_ref()`](functions::Max::max_by_ref) and [`min_by_ref()`](functions::Min::min_by_ref).
///   - From [`TotalCmp`]: [`total_cmp()`](TotalCmp::total_cmp) for a total ordering compliant with IEEE 754.
///   - From [`Clamp`]: [`clamp_ref()`](Clamp::clamp_ref).
///
/// - **Specialized Functions:**
///   - From [`ATan2`]: [`atan2()`](ATan2::atan2).
///   - From [`ExpM1`]/[`Ln1p`]: [`exp_m1()`](ExpM1::exp_m1) and [`ln_1p()`](Ln1p::ln_1p).
///   - From [`Hypot`]: [`hypot()`](Hypot::hypot) for computing sqrt(a² + b²).
///   - From [`Classify`]: [`classify()`](Classify::classify).
///
/// - **Fused Multiply-Add Variants:**
///   [`kernel_mul_add_mul_mut()`](Self::kernel_mul_add_mul_mut) and
///   [`kernel_mul_sub_mul_mut()`](Self::kernel_mul_sub_mul_mut).
///
/// ### Constants and Utilities
///
/// ```rust
/// use num_valid::{RealNative64StrictFinite, Constants};
///
/// let pi = RealNative64StrictFinite::pi();
/// let e = RealNative64StrictFinite::e();
/// let eps = RealNative64StrictFinite::epsilon();
/// let max_val = RealNative64StrictFinite::max_finite();
/// ```
///
/// ## Naming Convention for `kernel_*` Methods
///
/// Methods prefixed with `kernel_` (e.g., `kernel_ceil`, `kernel_copysign`) are
/// part of the low-level kernel interface. They typically delegate directly to the
/// most efficient implementation for the underlying type (like `f64::ceil`) without
/// adding extra validation layers. They are intended to be fast primitives upon which
/// safer, higher-level abstractions can be built.
///
/// ## Critical Trait Bounds
///
/// - `Self: FpScalar<RealType = Self>`: This is the defining constraint. It ensures that the type
///   has all basic floating-point capabilities and confirms that its associated real type is itself.
/// - `Self: PartialOrd + PartialOrd<f64>`: These bounds are essential for comparison operations,
///   allowing instances to be compared both with themselves and with native `f64` constants.
///
/// ## Backend-Specific Behavior
///
/// ### Native `f64` Backend
/// - Direct delegation to standard library functions
/// - IEEE 754 compliance
/// - Maximum performance
///
/// ### Arbitrary-Precision (`rug`) Backend
/// - Configurable precision at compile-time
/// - Exact arithmetic within precision limits
/// - [`try_from_f64()`](Self::try_from_f64) validates exact representability
///
/// ## Error Handling
///
/// Operations that can fail provide both panicking and non-panicking variants:
/// ```rust
/// use num_valid::{RealNative64StrictFinite, functions::Sqrt};
/// use try_create::TryNew;
///
/// let positive = RealNative64StrictFinite::try_new(4.0).unwrap();
/// let negative = RealNative64StrictFinite::try_new(-4.0).unwrap();
///
/// // Panicking version (use when input validity is guaranteed)
/// let sqrt_pos = positive.sqrt();
/// assert_eq!(*sqrt_pos.as_ref(), 2.0);
///
/// // Non-panicking version (use for potentially invalid inputs)
/// let sqrt_neg_result = negative.try_sqrt();
/// assert!(sqrt_neg_result.is_err());
/// ```
pub trait RealScalar:
    FpScalar<RealType = Self, InnerType = Self::RawReal>
    + Sign
    + Rounding
    + Constants
    + PartialEq<f64>
    + PartialOrd
    + PartialOrd<f64>
    + Max
    + Min
    + ATan2
    + for<'a> Pow<&'a Self, Error = PowRealBaseRealExponentErrors<Self::RawReal>>
    + Clamp
    + Classify
    + ExpM1
    + Hypot
    + Ln1p
    + TotalCmp
    + TryFrom<f64>
{
    /// The most fundamental, "raw" representation of this real number.
    ///
    /// This type provides the foundation for all mathematical operations and
    /// is used to parameterize error types for this scalar.
    ///
    /// # Examples
    /// - For [`f64`]: `RawReal = f64`
    /// - For [`RealNative64StrictFinite`]: `RawReal = f64`
    /// - For `RealRugStrictFinite<P>`: `RawReal = rug::Float`
    type RawReal: RawRealTrait;

    /// Multiplies two products and adds them in one fused operation, rounding to the nearest with only one rounding error.
    /// `a.kernel_mul_add_mul_mut(&b, &c, &d)` produces a result like `&a * &b + &c * &d`, but stores the result in `a` using its precision.
    fn kernel_mul_add_mul_mut(&mut self, mul: &Self, add_mul1: &Self, add_mul2: &Self);

    /// Multiplies two products and subtracts them in one fused operation, rounding to the nearest with only one rounding error.
    /// `a.kernel_mul_sub_mul_mut(&b, &c, &d)` produces a result like `&a * &b - &c * &d`, but stores the result in `a` using its precision.
    fn kernel_mul_sub_mul_mut(&mut self, mul: &Self, sub_mul1: &Self, sub_mul2: &Self);

    /// Tries to create an instance of `Self` from a [`f64`].
    ///
    /// This conversion is fallible and validates the input `value`. For `rug`-based types,
    /// it also ensures that the `f64` can be represented exactly at the target precision.
    ///
    /// # Errors
    /// Returns [`ErrorsTryFromf64`] if the `value` is not finite or cannot be
    /// represented exactly by `Self`.
    ///
    /// # Examples
    ///
    /// ## Quick Creation (Using Macros - Recommended)
    /// ```
    /// use num_valid::real;
    ///
    /// let x = real!(3.14);  // Concise, panics on invalid input
    /// let pi = real!(std::f64::consts::PI);
    /// ```
    ///
    /// ## Explicit Creation (Error Handling)
    /// ```
    /// use num_valid::{RealNative64StrictFinite, RealScalar};
    ///
    /// // Fallible - returns Result
    /// let x = RealNative64StrictFinite::try_from_f64(3.14)?;
    /// assert_eq!(x.as_ref(), &3.14);
    ///
    /// // Invalid value (NaN)
    /// assert!(RealNative64StrictFinite::try_from_f64(f64::NAN).is_err());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// See also: [`real!`] macro for the most ergonomic way to create validated real numbers.
    #[must_use = "this `Result` may contain an error that should be handled"]
    fn try_from_f64(value: f64) -> Result<Self, ErrorsTryFromf64<Self::RawReal>>;

    /// Creates an instance of `Self` from a [`f64`], panicking if the value is invalid.
    ///
    /// This is a convenience method for cases where you know the value is valid (e.g., constants).
    /// For error handling without panics, use [`try_from_f64`](Self::try_from_f64).
    ///
    /// # Panics
    ///
    /// Panics if the input value fails validation (e.g., NaN, infinity, or subnormal for strict policies).
    ///
    /// # Examples
    ///
    /// ```
    /// use num_valid::{RealNative64StrictFinite, RealScalar};
    ///
    /// // Valid constants - cleaner syntax without unwrap()
    /// let pi = RealNative64StrictFinite::from_f64(std::f64::consts::PI);
    /// let e = RealNative64StrictFinite::from_f64(std::f64::consts::E);
    /// let sqrt2 = RealNative64StrictFinite::from_f64(std::f64::consts::SQRT_2);
    ///
    /// assert_eq!(pi.as_ref(), &std::f64::consts::PI);
    /// ```
    ///
    /// ```should_panic
    /// use num_valid::{RealNative64StrictFinite, RealScalar};
    ///
    /// // This will panic because NaN is invalid
    /// let invalid = RealNative64StrictFinite::from_f64(f64::NAN);
    /// ```
    fn from_f64(value: f64) -> Self {
        Self::try_from_f64(value).expect("RealScalar::from_f64() failed: invalid f64 value")
    }

    /// Safely converts the truncated value to `usize`.
    ///
    /// Truncates toward zero and validates the result is a valid `usize`.
    ///
    /// # Returns
    ///
    /// - `Ok(usize)`: If truncated value is in `0..=usize::MAX`
    /// - `Err(_)`: If value is not finite or out of range
    ///
    /// # Examples
    ///
    /// ```rust
    /// use num_valid::{RealNative64StrictFinite, RealScalar};
    /// use try_create::TryNew;
    ///
    /// let x = RealNative64StrictFinite::try_new(42.9)?;
    /// assert_eq!(x.truncate_to_usize()?, 42);
    ///
    /// let neg = RealNative64StrictFinite::try_new(-1.0)?;
    /// assert!(neg.truncate_to_usize().is_err());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// <details>
    /// <summary>Detailed Behavior and Edge Cases</summary>
    ///
    /// ## Truncation Rules
    ///
    /// The fractional part is discarded, moving toward zero:
    /// - `3.7` → `3`
    /// - `-2.9` → `-2`
    /// - `0.9` → `0`
    ///
    /// ## Error Conditions
    ///
    /// - [`NotFinite`](ErrorsRawRealToInteger::NotFinite): Value is `NaN` or `±∞`
    /// - [`OutOfRange`](ErrorsRawRealToInteger::OutOfRange): Value is negative or > `usize::MAX`
    ///
    /// ## Additional Examples
    ///
    /// ```rust
    /// use num_valid::{RealNative64StrictFinite, RealScalar, core::errors::ErrorsRawRealToInteger};
    /// use try_create::TryNew;
    ///
    /// // Zero
    /// let zero = RealNative64StrictFinite::try_new(0.0)?;
    /// assert_eq!(zero.truncate_to_usize()?, 0);
    ///
    /// // Large valid values
    /// let large = RealNative64StrictFinite::try_new(1_000_000.7)?;
    /// assert_eq!(large.truncate_to_usize()?, 1_000_000);
    ///
    /// // Values too large for usize
    /// let too_large = RealNative64StrictFinite::try_new(1e20)?;
    /// assert!(matches!(too_large.truncate_to_usize(), Err(ErrorsRawRealToInteger::OutOfRange { .. })));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// ## Practical Usage
    ///
    /// ```rust
    /// use num_valid::{RealNative64StrictFinite, RealScalar};
    /// use try_create::TryNew;
    ///
    /// fn create_vector_with_size<T: Default + Clone>(
    ///     size_float: RealNative64StrictFinite
    /// ) -> Result<Vec<T>, Box<dyn std::error::Error>> {
    ///     let size = size_float.truncate_to_usize()?;
    ///     Ok(vec![T::default(); size])
    /// }
    ///
    /// let size = RealNative64StrictFinite::try_new(10.7)?;
    /// let vec: Vec<i32> = create_vector_with_size(size)?;
    /// assert_eq!(vec.len(), 10); // Truncated from 10.7
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// ## Comparison with Alternatives
    ///
    /// | Method | Behavior | Range Check | Fractional |
    /// |--------|----------|-------------|------------|
    /// | `truncate_to_usize()` | Towards zero | ✓ | Discarded |
    /// | `as usize` (raw) | Undefined | ✗ | Undefined |
    /// | `round().as usize` | Nearest | ✗ | Rounded |
    /// | `floor().as usize` | Towards -∞ | ✗ | Discarded |
    /// | `ceil().as usize` | Towards +∞ | ✗ | Discarded |
    ///
    /// ## Backend-Specific Notes
    ///
    /// - **Native f64**: Uses `az::CheckedAs` for safe conversion with overflow detection
    /// - **Arbitrary-precision (rug)**: Respects current precision, may adjust for very large numbers
    ///
    /// </details>
    fn truncate_to_usize(self) -> Result<usize, ErrorsRawRealToInteger<Self::RawReal, usize>> {
        let raw: Self::RawReal = self.into_inner();
        raw.truncate_to_usize()
    }
}

/// # Trait for complex scalar numbers
///
/// [`ComplexScalar`] is a specialized trait for complex number types that extends the
/// core [`FpScalar`] functionality with complex-specific operations. It provides a
/// unified interface for working with complex numbers across different validation
/// policies and underlying representations.
///
/// ## Design Philosophy
///
/// This trait bridges the gap between raw complex number operations and the validated
/// complex number types in [`num-valid`](crate). It ensures that complex-specific
/// operations like conjugation, argument calculation, and real-number scaling are
/// available in a type-safe, validated context.
///
/// ## Core Capabilities
///
/// The trait provides several key features:
///
/// - **Component manipulation**: Through [`ComplexScalarMutateParts`], allowing safe
///   modification of real and imaginary parts
/// - **Conjugation**: Via the [`functions::Conjugate`] trait for computing complex conjugates
/// - **Argument calculation**: Through [`functions::Arg`] for computing the phase angle
/// - **Real scaling**: Multiplication and assignment with real numbers
/// - **Power operations**: Raising complex numbers to real exponents
/// - **Convenience methods**: Like [`scale`](Self::scale) and [`scale_mut`](Self::scale_mut)
///   for efficient real-number scaling
///
/// ## Type Relationships
///
/// Types implementing [`ComplexScalar`] must also implement [`FpScalar`] with
/// `Kind = scalar_kind::Complex`, establishing them as complex number types within
/// the [`num-valid`](crate) type system.
///
/// # Quick Start
///
/// The easiest way to create complex numbers is using the [`complex!`] macro:
///
/// ```
/// use num_valid::complex;
///
/// let z1 = complex!(1.0, 2.0);   // 1 + 2i
/// let z2 = complex!(-3.0, 4.0);  // -3 + 4i
/// let i = complex!(0.0, 1.0);    // Imaginary unit
/// ```
///
/// For runtime values or error handling, use explicit construction:
///
/// ```
/// use num_valid::{ComplexNative64StrictFinite, functions::ComplexScalarConstructors};
/// use num::Complex;
/// use try_create::TryNew;
///
/// // From Complex<f64>
/// let z = ComplexNative64StrictFinite::try_new(Complex::new(3.0, 4.0))?;
///
/// // From two f64 values
/// let z = ComplexNative64StrictFinite::try_new_complex(3.0, 4.0)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// ## Usage Examples
///
/// ### Basic Complex Operations
/// ```rust
/// use num_valid::{ComplexNative64StrictFinite, RealNative64StrictFinite, ComplexScalar};
/// use num::Complex;
/// use try_create::TryNew;
///
/// let z = ComplexNative64StrictFinite::try_new(Complex::new(3.0, 4.0)).unwrap();
/// let factor = RealNative64StrictFinite::try_new(2.5).unwrap();
///
/// // Scale by a real number
/// let scaled = z.scale(&factor);
/// // Result: (7.5, 10.0)
/// ```
///
/// ### In-place Operations
/// ```rust
/// use num_valid::{ComplexNative64StrictFinite, RealNative64StrictFinite, ComplexScalar};
/// use num::Complex;
/// use try_create::TryNew;
///
/// let mut z = ComplexNative64StrictFinite::try_new(Complex::new(1.0, 2.0)).unwrap();
/// let factor = RealNative64StrictFinite::try_new(3.0).unwrap();
///
/// z.scale_mut(&factor);
/// // z is now (3.0, 6.0)
/// ```
///
/// ## See Also
///
/// - [`FpScalar`]: The base trait for all floating-point scalars
/// - [`RealScalar`]: The equivalent trait for real numbers
/// - [`ComplexScalarMutateParts`]: For component-wise operations
/// - [`functions`]: Module containing mathematical functions for complex numbers
/// - [`complex!`]: Macro for the most ergonomic way to create validated complex numbers
pub trait ComplexScalar:
    ComplexScalarMutateParts
    + Conjugate
    + Arg<Output = Self::RealType>
    + for<'a> Mul<&'a Self::RealType, Output = Self>
    + for<'a> MulAssign<&'a Self::RealType>
    + for<'a> Pow<&'a Self::RealType, Error = PowComplexBaseRealExponentErrors<Self::RawComplex>>
{
    /// Scale the complex number `self` by the real coefficient `c`.
    ///
    /// This is equivalent to complex multiplication by a real number,
    /// scaling both the real and imaginary parts by the same factor.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use num_valid::{ComplexNative64StrictFinite, RealNative64StrictFinite, ComplexScalar};
    /// use num::Complex;
    /// use try_create::TryNew;
    ///
    /// let z = ComplexNative64StrictFinite::try_new(Complex::new(3.0, 4.0)).unwrap();
    /// let factor = RealNative64StrictFinite::try_new(2.0).unwrap();
    ///
    /// let scaled = z.scale(&factor);
    /// // Result: (6.0, 8.0)
    /// ```
    #[inline(always)]
    fn scale(self, c: &Self::RealType) -> Self {
        self * c
    }

    /// Scale (in-place) the complex number `self` by the real coefficient `c`.
    ///
    /// This modifies the complex number in place, scaling both components
    /// by the real factor.
    ///
    /// ## Examples
    ///
    /// ```rust
    /// use num_valid::{ComplexNative64StrictFinite, RealNative64StrictFinite, ComplexScalar};
    /// use num::Complex;
    /// use try_create::TryNew;
    ///
    /// let mut z = ComplexNative64StrictFinite::try_new(Complex::new(3.0, 4.0)).unwrap();
    /// let factor = RealNative64StrictFinite::try_new(2.0).unwrap();
    ///
    /// z.scale_mut(&factor);
    /// // z is now (6.0, 8.0)
    /// ```
    #[inline(always)]
    fn scale_mut(&mut self, c: &Self::RealType) {
        *self *= c;
    }

    /// Consumes the complex number and returns its real and imaginary parts as a tuple.
    ///
    /// This method moves ownership of the complex number and extracts its two components,
    /// returning them as separate real scalar values. This is useful when you need to
    /// work with the components independently and no longer need the original complex value.
    ///
    /// # Returns
    ///
    /// A tuple `(real, imaginary)` where:
    /// - `real` is the real part of the complex number
    /// - `imaginary` is the imaginary part of the complex number
    ///
    /// # Examples
    ///
    /// ```rust
    /// use num_valid::{ComplexNative64StrictFinite, ComplexScalar};
    /// use num::Complex;
    /// use try_create::TryNew;
    ///
    /// let z = ComplexNative64StrictFinite::try_new(Complex::new(3.0, 4.0)).unwrap();
    ///
    /// // Consume z and extract its parts
    /// let (real, imag) = z.into_parts();
    ///
    /// assert_eq!(*real.as_ref(), 3.0);
    /// assert_eq!(*imag.as_ref(), 4.0);
    /// // z is no longer available here (moved)
    /// ```
    ///
    /// # See Also
    ///
    /// - [`ComplexScalarGetParts::real_part`]: Get the real part without consuming
    /// - [`ComplexScalarGetParts::imag_part`]: Get the imaginary part without consuming
    fn into_parts(self) -> (Self::RealType, Self::RealType);
}

//------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------
/// Attempts to convert a vector of [`f64`] values into a vector of the specified real scalar type.
///
/// This function provides a fallible conversion that validates each input value according
/// to the target type's validation policy. If any value fails validation, the entire
/// operation fails and returns an error.
///
/// ## Parameters
///
/// * `vec`: A vector of [`f64`] values to convert
///
/// ## Return Value
///
/// * `Ok(Vec<RealType>)`: If all values can be successfully converted and validated
/// * `Err(ErrorsTryFromf64)`: If any value fails validation, containing details about the failure
///
/// ## Usage Examples
///
/// ### Successful Conversion
/// ```rust
/// use num_valid::{try_vec_f64_into_vec_real, RealNative64StrictFinite};
///
/// let input = vec![1.0, -2.5, 3.14159];
/// let result = try_vec_f64_into_vec_real::<RealNative64StrictFinite>(input);
/// assert!(result.is_ok());
///
/// let validated_vec = result.unwrap();
/// assert_eq!(validated_vec.len(), 3);
/// assert_eq!(*validated_vec[0].as_ref(), 1.0);
/// ```
///
/// ### Failed Conversion
/// ```rust
/// use num_valid::{try_vec_f64_into_vec_real, RealNative64StrictFinite};
///
/// let input = vec![1.0, f64::NAN, 3.0]; // Contains NaN
/// let result = try_vec_f64_into_vec_real::<RealNative64StrictFinite>(input);
/// assert!(result.is_err()); // Fails due to NaN value
/// ```
#[inline(always)]
pub fn try_vec_f64_into_vec_real<RealType: RealScalar>(
    vec: Vec<f64>,
) -> Result<Vec<RealType>, ErrorsTryFromf64<RealType::RawReal>> {
    vec.into_iter().map(|v| RealType::try_from_f64(v)).collect()
}

/// Converts a vector of [`f64`] values into a vector of the specified real scalar type.
///
/// This is the panicking version of [`try_vec_f64_into_vec_real`]. It converts each
/// [`f64`] value to the target real scalar type, panicking if any conversion fails.
/// Use this function only when you are certain that all input values are valid for
/// the target type.
///
/// ## Parameters
///
/// * `vec`: A vector of [`f64`] values to convert
///
/// ## Return Value
///
/// A vector of validated real scalar values of type `RealType`.
///
/// ## Panics
///
/// Panics if any value in the input vector cannot be converted to `RealType`.
/// This can happen for various reasons:
/// - Input contains `NaN` or infinite values when using strict finite validation
/// - Precision loss when converting to arbitrary-precision types
/// - Values outside the representable range of the target type
///
/// ## Usage Examples
///
/// ### Successful Conversion
/// ```rust
/// use num_valid::{vec_f64_into_vec_real, RealNative64StrictFinite};
///
/// let input = vec![0.0, 1.0, -2.5, 3.14159];
/// let validated_vec: Vec<RealNative64StrictFinite> = vec_f64_into_vec_real(input);
///
/// assert_eq!(validated_vec.len(), 4);
/// assert_eq!(*validated_vec[0].as_ref(), 0.0);
/// assert_eq!(*validated_vec[1].as_ref(), 1.0);
/// ```
///
/// ## When to Use
///
/// - **Use this function when**: You are certain all input values are valid for the target type
/// - **Use [`try_vec_f64_into_vec_real`] when**: Input validation is uncertain and you want to handle errors gracefully
#[inline(always)]
pub fn vec_f64_into_vec_real<RealType: RealScalar>(vec: Vec<f64>) -> Vec<RealType> {
    try_vec_f64_into_vec_real(vec).expect(
        "The conversion from f64 to RealType failed, which should not happen in a well-defined numerical kernel."
    )
}
//------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------
/// A trait for types that can be randomly generated from a distribution over `f64`.
///
/// This trait provides a universal dispatch mechanism for generating random scalar values,
/// allowing a single generic API to work for primitive types like [`f64`] and
/// [`Complex<f64>`], as well as custom validated types like [`RealValidated`] and
/// [`ComplexValidated`].
///
/// ## Purpose
///
/// The primary goal of [`RandomSampleFromF64`] is to abstract the process of creating a random
/// scalar. Many random number distributions in the [`rand`] crate are defined to produce
/// primitive types like `f64`. This trait acts as a bridge, allowing those same
/// distributions to be used to generate more complex or validated types.
///
/// ## How It Works
///
/// The trait defines a single required method, [`RandomSampleFromF64::sample_from()`], which takes a reference
/// to any distribution that implements [`rand::distr::Distribution<f64>`] and a
/// random number generator (RNG). Each implementing type provides its own logic for
/// this method:
///
/// - For `f64`, it simply samples directly from the distribution.
/// - For `Complex<f64>`, it samples twice to create the real and imaginary parts.
/// - For [`RealValidated<K>`], it samples an `f64` and then passes it through the
///   validation and conversion logic of [`RealValidated::try_from_f64`].
/// - For [`ComplexValidated<K>`], it reuses the logic for `RealValidated<K>` to sample
///   the real and imaginary components.
///
/// ## Example
///
/// Here is how you can write a generic function that creates a vector of random numbers
/// for any type that implements [`RandomSampleFromF64`].
///
/// ```rust
/// use num_valid::{RealNative64StrictFinite, RealScalar, new_random_vec};
/// use rand::{distr::Uniform, rngs::StdRng, Rng, SeedableRng};
/// use try_create::IntoInner;
///
/// let seed = [42; 32]; // Example seed for reproducibility
/// let mut rng = StdRng::from_seed(seed);
/// let uniform = Uniform::new(-10.0, 10.0).unwrap();
///
/// // Create a vector of random f64 values.
/// let f64_vec: Vec<f64> = new_random_vec(3, &uniform, &mut rng);
/// assert_eq!(f64_vec.len(), 3);
///
/// // Create a vector of random validated real numbers using the same function.
/// // Reset RNG to get same sequence
/// let mut rng = StdRng::from_seed(seed);
/// let validated_vec: Vec<RealNative64StrictFinite> = new_random_vec(3, &uniform, &mut rng);
/// assert_eq!(validated_vec.len(), 3);
///
/// // The underlying numerical values should be identical because the RNG was seeded the same.
/// assert_eq!(&f64_vec[0], validated_vec[0].as_ref());
/// assert_eq!(&f64_vec[1], validated_vec[1].as_ref());
/// assert_eq!(&f64_vec[2], validated_vec[2].as_ref());
/// ```
pub trait RandomSampleFromF64: Sized + Clone {
    /// Samples a single value of `Self` using the given `f64` distribution.
    fn sample_from<D, R>(dist: &D, rng: &mut R) -> Self
    where
        D: Distribution<f64>,
        R: Rng + ?Sized;

    /// Creates an iterator that samples `n` values from the given distribution.
    ///
    /// This is a convenience method that generates multiple random samples at once.
    /// It returns an iterator that lazily samples from the distribution.
    ///
    /// # Arguments
    ///
    /// * `dist` - The probability distribution to sample from.
    /// * `rng` - The random number generator to use.
    /// * `n` - The number of samples to generate.
    ///
    /// # Returns
    ///
    /// An iterator that yields `n` samples of type `Self`.
    fn sample_iter_from<D, R>(dist: &D, rng: &mut R, n: usize) -> impl Iterator<Item = Self>
    where
        D: Distribution<f64>,
        R: Rng + ?Sized,
    {
        // Create an iterator that samples `n` values from the distribution.
        (0..n).map(move |_| Self::sample_from(dist, rng))
    }
}

impl RandomSampleFromF64 for f64 {
    #[inline]
    fn sample_from<D, R>(dist: &D, rng: &mut R) -> Self
    where
        D: Distribution<f64>,
        R: Rng + ?Sized,
    {
        // Straightforward implementation: sample a f64.
        dist.sample(rng)
    }
}
impl RandomSampleFromF64 for Complex<f64> {
    #[inline]
    fn sample_from<D, R>(dist: &D, rng: &mut R) -> Self
    where
        D: Distribution<f64>,
        R: Rng + ?Sized,
    {
        // Sample two f64 for the real and imaginary parts.
        let re = dist.sample(rng);
        let im = dist.sample(rng);
        Complex::new(re, im)
    }
}

impl<K> RandomSampleFromF64 for RealValidated<K>
where
    K: NumKernel,
{
    #[inline]
    fn sample_from<D, R>(dist: &D, rng: &mut R) -> Self
    where
        D: Distribution<f64>,
        R: Rng + ?Sized,
    {
        loop {
            // Sample a f64 and then convert/validate it.
            // The loop ensures that a valid value is returned
            let value_f64 = dist.sample(rng);
            let value = RealValidated::try_from_f64(value_f64);
            if let Ok(validated_value) = value {
                return validated_value;
            }
        }
    }
}

impl<K> RandomSampleFromF64 for ComplexValidated<K>
where
    K: NumKernel,
{
    #[inline]
    fn sample_from<D, R>(dist: &D, rng: &mut R) -> Self
    where
        D: Distribution<f64>,
        R: Rng + ?Sized,
    {
        // Reuse the RealValidated sampling logic for both parts.
        let re = RealValidated::<K>::sample_from(dist, rng);
        let im = RealValidated::<K>::sample_from(dist, rng);
        ComplexValidated::new_complex(re, im)
    }
}

//------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------
/// Generates a `Vec<T>` of a specified length with random values.
///
/// This function leverages the [`RandomSampleFromF64`] trait to provide a universal way
/// to create a vector of random numbers for any supported scalar type, including
/// primitive types like `f64` and `Complex<f64>`, as well as validated types
/// like [`RealValidated`] and [`ComplexValidated`].
///
/// # Parameters
///
/// * `n`: The number of random values to generate in the vector.
/// * `distribution`: A reference to any distribution from the `rand` crate that
///   implements `Distribution<f64>` (e.g., `Uniform`, `StandardNormal`).
/// * `rng`: A mutable reference to a random number generator that implements `Rng`.
///
/// # Type Parameters
///
/// * `T`: The scalar type of the elements in the returned vector. Must implement [`RandomSampleFromF64`].
/// * `D`: The type of the distribution.
/// * `R`: The type of the random number generator.
///
/// # Example
///
/// # Example
///
/// ```rust
/// use num_valid::{new_random_vec, RealNative64StrictFinite};
/// use rand::{distr::Uniform, rngs::StdRng, SeedableRng};
/// use try_create::IntoInner;
///
/// let seed = [42; 32]; // Use a fixed seed for a reproducible example
///
/// // Generate a vector of random f64 values.
/// let mut rng_f64 = StdRng::from_seed(seed);
/// let uniform = Uniform::new(-10.0, 10.0).unwrap();
/// let f64_vec: Vec<f64> = new_random_vec(3, &uniform, &mut rng_f64);
///
/// // Generate a vector of random validated real numbers using the same seed.
/// let mut rng_validated = StdRng::from_seed(seed);
/// let validated_vec: Vec<RealNative64StrictFinite> = new_random_vec(3, &uniform, &mut rng_validated);
///
/// assert_eq!(f64_vec.len(), 3);
/// assert_eq!(validated_vec.len(), 3);
///
/// // The underlying numerical values should be identical because the RNG was seeded the same.
/// assert_eq!(&f64_vec[0], validated_vec[0].as_ref());
/// assert_eq!(&f64_vec[1], validated_vec[1].as_ref());
/// assert_eq!(&f64_vec[2], validated_vec[2].as_ref());
/// ```
pub fn new_random_vec<T, D, R>(n: usize, distribution: &D, rng: &mut R) -> Vec<T>
where
    T: RandomSampleFromF64,
    D: Distribution<f64>,
    R: Rng + ?Sized,
{
    T::sample_iter_from(distribution, rng, n).collect()
}
//------------------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    use num::Complex;
    use num_traits::MulAddAssign;
    use std::ops::{Add, Div, Sub};

    mod functions_general_type {
        use super::*;

        fn test_recip<RealType: RealScalar>() {
            let a = RealType::two();

            let a = a.try_reciprocal().unwrap();
            let expected = RealType::one_div_2();
            assert_eq!(a, expected);
        }

        fn test_zero<RealType: RealScalar>() {
            let a = RealType::zero();

            assert_eq!(a, 0.0);
        }

        fn test_one<RealType: RealScalar>() {
            let a = RealType::one();

            assert_eq!(a, 1.0);
        }

        fn test_add<ScalarType: FpScalar>(a: ScalarType, b: ScalarType, c_expected: ScalarType)
        where
            for<'a> &'a ScalarType:
                Add<ScalarType, Output = ScalarType> + Add<&'a ScalarType, Output = ScalarType>,
        {
            let c = a.clone() + &b;
            assert_eq!(c, c_expected);

            let c = &a + b.clone();
            assert_eq!(c, c_expected);

            let c = a.clone() + b.clone();
            assert_eq!(c, c_expected);

            let c = &a + &b;
            assert_eq!(c, c_expected);
        }

        fn test_sub<ScalarType: FpScalar>(a: ScalarType, b: ScalarType, c_expected: ScalarType)
        where
            for<'a> &'a ScalarType:
                Sub<ScalarType, Output = ScalarType> + Sub<&'a ScalarType, Output = ScalarType>,
        {
            let c = a.clone() - &b;
            assert_eq!(c, c_expected);

            let c = &a - b.clone();
            assert_eq!(c, c_expected);

            let c = a.clone() - b.clone();
            assert_eq!(c, c_expected);

            let c = &a - &b;
            assert_eq!(c, c_expected);
        }

        fn test_mul<ScalarType: FpScalar>(a: ScalarType, b: ScalarType, c_expected: ScalarType)
        where
            for<'a> &'a ScalarType:
                Mul<ScalarType, Output = ScalarType> + Mul<&'a ScalarType, Output = ScalarType>,
        {
            let c = a.clone() * &b;
            assert_eq!(c, c_expected);

            let c = &a * b.clone();
            assert_eq!(c, c_expected);

            let c = a.clone() * b.clone();
            assert_eq!(c, c_expected);

            let c = &a * &b;
            assert_eq!(c, c_expected);
        }

        fn test_div<ScalarType: FpScalar>(a: ScalarType, b: ScalarType, c_expected: ScalarType)
        where
            for<'a> &'a ScalarType:
                Div<ScalarType, Output = ScalarType> + Div<&'a ScalarType, Output = ScalarType>,
        {
            let c = a.clone() / &b;
            assert_eq!(c, c_expected);

            let c = &a / b.clone();
            assert_eq!(c, c_expected);

            let c = a.clone() / b.clone();
            assert_eq!(c, c_expected);

            let c = &a / &b;
            assert_eq!(c, c_expected);
        }

        fn test_mul_complex_with_real<ComplexType: ComplexScalar>(
            a: ComplexType,
            b: ComplexType::RealType,
            a_times_b_expected: ComplexType,
        ) {
            let a_times_b = a.clone().scale(&b);
            assert_eq!(a_times_b, a_times_b_expected);

            let a_times_b = a.clone() * &b;
            assert_eq!(a_times_b, a_times_b_expected);

            /*
            let b_times_a_expected = a_times_b_expected.clone();

            let b_times_a = &b * a.clone();
            assert_eq!(b_times_a, b_times_a_expected);

            let b_times_a = b.clone() * a.clone();
            assert_eq!(b_times_a, b_times_a_expected);
            */
        }

        fn test_mul_assign_complex_with_real<ComplexType: ComplexScalar>(
            a: ComplexType,
            b: ComplexType::RealType,
            a_times_b_expected: ComplexType,
        ) {
            let mut a_times_b = a.clone();
            a_times_b.scale_mut(&b);
            assert_eq!(a_times_b, a_times_b_expected);

            //        let mut a_times_b = a.clone();
            //        a_times_b *= b;
            //        assert_eq!(a_times_b, a_times_b_expected);
        }

        fn test_neg_assign_real<RealType: RealScalar>() {
            let mut a = RealType::one();
            a.neg_assign();

            let a_expected = RealType::try_from_f64(-1.).unwrap();
            assert_eq!(a, a_expected);
        }

        fn test_add_assign_real<RealType: RealScalar>() {
            let mut a = RealType::try_from_f64(1.0).unwrap();
            let b = RealType::try_from_f64(2.0).unwrap();

            a += &b;
            let a_expected = RealType::try_from_f64(3.0).unwrap();
            assert_eq!(a, a_expected);

            a += b;
            let a_expected = RealType::try_from_f64(5.0).unwrap();
            assert_eq!(a, a_expected);
        }

        fn test_sub_assign_real<RealType: RealScalar>() {
            let mut a = RealType::try_from_f64(1.0).unwrap();
            let b = RealType::try_from_f64(2.0).unwrap();

            a -= &b;
            let a_expected = RealType::try_from_f64(-1.0).unwrap();
            assert_eq!(a, a_expected);

            a -= b;
            let a_expected = RealType::try_from_f64(-3.0).unwrap();
            assert_eq!(a, a_expected);
        }

        fn test_mul_assign_real<RealType: RealScalar>() {
            let mut a = RealType::try_from_f64(1.0).unwrap();
            let b = RealType::try_from_f64(2.0).unwrap();

            a *= &b;
            let a_expected = RealType::try_from_f64(2.0).unwrap();
            assert_eq!(a, a_expected);

            a *= b;
            let a_expected = RealType::try_from_f64(4.0).unwrap();
            assert_eq!(a, a_expected);
        }

        fn test_div_assign_real<RealType: RealScalar>() {
            let mut a = RealType::try_from_f64(4.0).unwrap();
            let b = RealType::try_from_f64(2.0).unwrap();

            a /= &b;
            let a_expected = RealType::try_from_f64(2.0).unwrap();
            assert_eq!(a, a_expected);

            a /= b;
            let a_expected = RealType::try_from_f64(1.0).unwrap();
            assert_eq!(a, a_expected);
        }

        fn test_mul_add_ref_real<RealType: RealScalar>() {
            let a = RealType::try_from_f64(2.0).unwrap();
            let b = RealType::try_from_f64(3.0).unwrap();
            let c = RealType::try_from_f64(1.0).unwrap();

            let d_expected = RealType::try_from_f64(7.0).unwrap();

            let d = a.mul_add_ref(&b, &c);
            assert_eq!(d, d_expected);
        }

        fn test_sin_real<RealType: RealScalar>() {
            let a = RealType::zero();

            let a = a.sin();
            let expected = RealType::zero();
            assert_eq!(a, expected);
        }

        fn test_cos_real<RealType: RealScalar>() {
            let a = RealType::zero();

            let a = a.cos();
            let expected = RealType::one();
            assert_eq!(a, expected);
        }

        fn test_abs_real<RealType: RealScalar>() {
            let a = RealType::try_from_f64(-1.).unwrap();

            let abs: RealType = a.abs();
            let expected = RealType::one();
            assert_eq!(abs, expected);
        }

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn zero() {
                    test_zero::<f64>();
                }

                #[test]
                fn one() {
                    test_one::<f64>();
                }

                #[test]
                fn recip() {
                    test_recip::<f64>();
                }

                #[test]
                fn add() {
                    let a = 1.0;
                    let b = 2.0;
                    let c_expected = 3.0;
                    test_add(a, b, c_expected);
                }

                #[test]
                fn sub() {
                    let a = 1.0;
                    let b = 2.0;
                    let c_expected = -1.0;
                    test_sub(a, b, c_expected);
                }

                #[test]
                fn mul() {
                    let a = 2.0;
                    let b = 3.0;
                    let c_expected = 6.0;
                    test_mul(a, b, c_expected);
                }

                #[test]
                fn div() {
                    let a = 6.;
                    let b = 2.;
                    let c_expected = 3.;
                    test_div(a, b, c_expected);
                }

                #[test]
                fn neg_assign() {
                    test_neg_assign_real::<f64>();
                }

                #[test]
                fn add_assign() {
                    test_add_assign_real::<f64>();
                }

                #[test]
                fn sub_assign() {
                    test_sub_assign_real::<f64>();
                }

                #[test]
                fn mul_assign() {
                    test_mul_assign_real::<f64>();
                }

                #[test]
                fn div_assign() {
                    test_div_assign_real::<f64>();
                }
                #[test]
                fn mul_add_ref() {
                    test_mul_add_ref_real::<f64>();
                }

                #[test]
                fn from_f64() {
                    let v_native64 = f64::try_from_f64(16.25).unwrap();
                    assert_eq!(v_native64, 16.25);
                }

                #[test]
                fn abs() {
                    test_abs_real::<f64>();
                }

                #[test]
                fn acos() {
                    let a = 0.;

                    let pi_over_2 = a.acos();
                    let expected = std::f64::consts::FRAC_PI_2;
                    assert_eq!(pi_over_2, expected);
                }

                #[test]
                fn asin() {
                    let a = 1.;

                    let pi_over_2 = a.asin();
                    let expected = std::f64::consts::FRAC_PI_2;
                    assert_eq!(pi_over_2, expected);
                }

                #[test]
                fn cos() {
                    test_cos_real::<f64>();
                }

                #[test]
                fn sin() {
                    test_sin_real::<f64>();
                }

                #[test]
                fn test_acos() {
                    let value: f64 = 0.5;
                    let result = value.acos();
                    assert_eq!(result, value.acos());
                }

                #[test]
                fn test_acosh() {
                    let value: f64 = 1.5;
                    let result = value.acosh();
                    assert_eq!(result, value.acosh());
                }

                #[test]
                fn test_asin() {
                    let value: f64 = 0.5;
                    let result = value.asin();
                    assert_eq!(result, value.asin());
                }

                #[test]
                fn test_asinh() {
                    let value: f64 = 0.5;
                    let result = value.asinh();
                    assert_eq!(result, value.asinh());
                }

                #[test]
                fn test_atan() {
                    let value: f64 = 0.5;
                    let result = value.atan();
                    assert_eq!(result, value.atan());
                }

                #[test]
                fn test_atanh() {
                    let value: f64 = 0.5;
                    let result = value.atanh();
                    assert_eq!(result, value.atanh());
                }

                #[test]
                fn test_cos_02() {
                    let value: f64 = 0.5;
                    let result = value.cos();
                    assert_eq!(result, value.cos());
                }

                #[test]
                fn test_cosh() {
                    let value: f64 = 0.5;
                    let result = value.cosh();
                    assert_eq!(result, value.cosh());
                }

                #[test]
                fn test_exp() {
                    let value: f64 = 0.5;
                    let result = value.exp();
                    println!("result = {result:?}");

                    assert_eq!(result, value.exp());
                }

                #[test]
                fn test_is_finite() {
                    let value: f64 = 0.5;
                    assert!(value.is_finite());

                    let value: f64 = f64::INFINITY;
                    assert!(!value.is_finite());
                }

                #[test]
                fn test_is_infinite() {
                    let value: f64 = f64::INFINITY;
                    assert!(value.is_infinite());

                    let value: f64 = 0.5;
                    assert!(!value.is_infinite());
                }

                #[test]
                fn test_ln() {
                    let value: f64 = std::f64::consts::E;
                    let result = value.ln();
                    println!("result = {result:?}");
                    assert_eq!(result, value.ln());
                }

                #[test]
                fn test_log10() {
                    let value: f64 = 10.0;
                    let result = value.log10();
                    println!("result = {result:?}");
                    assert_eq!(result, value.log10());
                }

                #[test]
                fn test_log2() {
                    let value: f64 = 8.0;
                    let result = value.log2();
                    println!("result = {result:?}");
                    assert_eq!(result, value.log2());
                }

                #[test]
                fn test_recip_02() {
                    let value: f64 = 2.0;
                    let result = value.try_reciprocal().unwrap();
                    assert_eq!(result, value.recip());
                }

                #[test]
                fn test_sin_02() {
                    let value: f64 = 0.5;
                    let result = value.sin();
                    assert_eq!(result, value.sin());
                }

                #[test]
                fn test_sinh() {
                    let value: f64 = 0.5;
                    let result = value.sinh();
                    assert_eq!(result, value.sinh());
                }

                #[test]
                fn sqrt() {
                    let value: f64 = 4.0;
                    let result = value.sqrt();
                    assert_eq!(result, value.sqrt());
                }

                #[test]
                fn try_sqrt() {
                    let value: f64 = 4.0;
                    let result = value.try_sqrt().unwrap();
                    assert_eq!(result, value.sqrt());

                    assert!((-1.0).try_sqrt().is_err());
                }

                #[test]
                fn test_tan() {
                    let value: f64 = 0.5;
                    let result = value.tan();
                    assert_eq!(result, value.tan());
                }

                #[test]
                fn test_tanh() {
                    let value: f64 = 0.5;
                    let result = value.tanh();
                    assert_eq!(result, value.tanh());
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn add() {
                    let a = Complex::new(1., 2.);
                    let b = Complex::new(3., 4.);

                    let c_expected = Complex::new(4., 6.);

                    test_add(a, b, c_expected);
                }

                #[test]
                fn sub() {
                    let a = Complex::new(3., 2.);
                    let b = Complex::new(1., 4.);

                    let c_expected = Complex::new(2., -2.);

                    test_sub(a, b, c_expected);
                }

                #[test]
                fn mul() {
                    let a = Complex::new(3., 2.);
                    let b = Complex::new(1., 4.);
                    let c_expected = Complex::new(-5., 14.);
                    test_mul(a, b, c_expected);
                }

                #[test]
                fn div() {
                    let a = Complex::new(-5., 14.);
                    let b = Complex::new(1., 4.);

                    let c_expected = Complex::new(3., 2.);

                    test_div(a, b, c_expected);
                }

                #[test]
                fn add_assign() {
                    let mut a = Complex::new(1., 2.);
                    let b = Complex::new(3., 4.);

                    a += &b;
                    let a_expected = Complex::new(4., 6.);
                    assert_eq!(a, a_expected);

                    a += b;
                    let a_expected = Complex::new(7., 10.);
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn sub_assign() {
                    let mut a = Complex::new(3., 2.);
                    let b = Complex::new(2., 4.);

                    a -= &b;
                    let a_expected = Complex::new(1., -2.);
                    assert_eq!(a, a_expected);

                    a -= b;
                    let a_expected = Complex::new(-1., -6.);
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn mul_assign() {
                    let mut a = Complex::new(3., 2.);
                    let b = Complex::new(2., 4.);

                    a *= &b;
                    let a_expected = Complex::new(-2., 16.);
                    assert_eq!(a, a_expected);

                    a *= b;
                    let a_expected = Complex::new(-68., 24.);
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn div_assign() {
                    let mut a = Complex::new(-68., 24.);
                    let b = Complex::new(2., 4.);

                    a /= &b;
                    let a_expected = Complex::new(-2., 16.);
                    assert_eq!(a, a_expected);

                    a /= b;
                    let a_expected = Complex::new(3., 2.);
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn from_f64() {
                    let v = Complex::new(16.25, 2.);
                    assert_eq!(v.real_part(), 16.25);
                    assert_eq!(v.imag_part(), 2.);
                }

                #[test]
                fn conj() {
                    let v = Complex::new(16.25, 2.);

                    let v_conj = v.conjugate();
                    assert_eq!(v_conj.real_part(), 16.25);
                    assert_eq!(v_conj.imag_part(), -2.);
                }

                #[test]
                fn neg_assign() {
                    let mut a = Complex::new(1., 2.);
                    a.neg_assign();

                    let a_expected = Complex::new(-1., -2.);
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn abs() {
                    let a = Complex::new(-3., 4.);

                    let abs = a.abs();
                    let expected = 5.;
                    assert_eq!(abs, expected);
                }

                #[test]
                fn mul_add_ref() {
                    let a = Complex::new(2., -3.);
                    let b = Complex::new(3., 1.);
                    let c = Complex::new(1., -4.);

                    let d_expected = Complex::new(10., -11.);

                    let d = a.mul_add_ref(&b, &c);
                    assert_eq!(d, d_expected);
                }

                #[test]
                fn mul_complex_with_real() {
                    let a = Complex::new(1., 2.);
                    let b = 3.;

                    let a_times_b_expected = Complex::new(3., 6.);

                    test_mul_complex_with_real(a, b, a_times_b_expected);
                }

                #[test]
                fn mul_assign_complex_with_real() {
                    let a = Complex::new(1., 2.);
                    let b = 3.;

                    let a_times_b_expected = Complex::new(3., 6.);

                    test_mul_assign_complex_with_real(a, b, a_times_b_expected);
                }

                #[test]
                fn test_acos() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.acos();
                    assert_eq!(result, value.acos());
                }

                #[test]
                fn test_acosh() {
                    let value: Complex<f64> = Complex::new(1.5, 0.5);
                    let result = value.acosh();
                    assert_eq!(result, value.acosh());
                }

                #[test]
                fn test_asin() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.asin();
                    assert_eq!(result, value.asin());
                }

                #[test]
                fn test_asinh() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.asinh();
                    assert_eq!(result, value.asinh());
                }

                #[test]
                fn test_atan() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.atan();
                    assert_eq!(result, value.atan());
                }

                #[test]
                fn test_atanh() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.atanh();
                    assert_eq!(result, value.atanh());
                }

                #[test]
                fn test_cos_01() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.cos();
                    assert_eq!(result, value.cos());
                }

                #[test]
                fn test_cosh() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.cosh();
                    assert_eq!(result, value.cosh());
                }

                #[test]
                fn test_exp() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.exp();
                    println!("result = {result:?}");
                    assert_eq!(result, value.exp());
                }

                /*
                #[test]
                fn test_is_finite() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    assert!(value.is_finite());

                    let value: Complex<f64> = Complex::new(f64::INFINITY, 0.5);
                    assert!(!value.is_finite());
                }

                #[test]
                fn test_is_infinite() {
                    let value: Complex<f64> = Complex::new(f64::INFINITY, 0.5);
                    assert!(value.is_infinite());

                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    assert!(!value.is_infinite());
                }
                */

                #[test]
                fn test_ln() {
                    let value: Complex<f64> = Complex::new(std::f64::consts::E, 1.0);
                    let result = value.ln();
                    println!("result = {result:?}");
                    assert_eq!(result, value.ln());
                }

                #[test]
                fn test_log10() {
                    let value: Complex<f64> = Complex::new(10.0, 1.0);
                    let result = value.log10();
                    println!("result = {result:?}");
                    assert_eq!(result, value.log10());
                }

                #[test]
                fn test_log2() {
                    let value: Complex<f64> = Complex::new(8.0, 1.0);
                    let result = value.log2();
                    println!("result = {result:?}");
                    assert_eq!(result, value.log2());
                }

                #[test]
                fn test_recip() {
                    let value: Complex<f64> = Complex::new(2.0, 0.0);
                    let result = value.try_reciprocal().unwrap();
                    assert_eq!(result, value.finv());
                }

                #[test]
                fn test_sin_01() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.sin();
                    assert_eq!(result, value.sin());
                }

                #[test]
                fn test_sinh() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.sinh();
                    assert_eq!(result, value.sinh());
                }

                #[test]
                fn sqrt() {
                    let value: Complex<f64> = Complex::new(4.0, 1.0);
                    let result = value.sqrt();
                    assert_eq!(result, value.sqrt());
                }

                #[test]
                fn try_sqrt() {
                    let value: Complex<f64> = Complex::new(4.0, 1.0);
                    let result = value.try_sqrt().unwrap();
                    assert_eq!(result, value.sqrt());
                }

                #[test]
                fn test_tan() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.tan();
                    assert_eq!(result, value.tan());
                }

                #[test]
                fn test_tanh() {
                    let value: Complex<f64> = Complex::new(0.5, 0.5);
                    let result = value.tanh();
                    assert_eq!(result, value.tanh());
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug_ {
            use super::*;
            use crate::backends::rug::validated::{ComplexRugStrictFinite, RealRugStrictFinite};
            use rug::ops::CompleteRound;
            use try_create::{IntoInner, TryNew};

            const PRECISION: u32 = 100;

            mod real {
                use super::*;
                use rug::Float;

                #[test]
                fn zero() {
                    test_zero::<RealRugStrictFinite<64>>();
                    test_zero::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn one() {
                    test_one::<RealRugStrictFinite<64>>();
                    test_one::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn recip() {
                    test_recip::<RealRugStrictFinite<64>>();
                    test_recip::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn add() {
                    let a = RealRugStrictFinite::<PRECISION>::try_from_f64(1.0).unwrap();
                    let b = RealRugStrictFinite::<PRECISION>::try_from_f64(2.0).unwrap();
                    let c_expected = RealRugStrictFinite::<PRECISION>::try_from_f64(3.0).unwrap();
                    test_add(a, b, c_expected);
                }

                #[test]
                fn sub() {
                    let a = RealRugStrictFinite::<PRECISION>::try_from_f64(1.0).unwrap();
                    let b = RealRugStrictFinite::<PRECISION>::try_from_f64(2.0).unwrap();
                    let c_expected = RealRugStrictFinite::<PRECISION>::try_from_f64(-1.0).unwrap();
                    test_sub(a, b, c_expected);
                }

                #[test]
                fn mul() {
                    let a = RealRugStrictFinite::<PRECISION>::try_from_f64(2.0).unwrap();
                    let b = RealRugStrictFinite::<PRECISION>::try_from_f64(3.0).unwrap();
                    let c_expected = RealRugStrictFinite::<PRECISION>::try_from_f64(6.0).unwrap();
                    test_mul(a, b, c_expected);
                }

                #[test]
                fn div() {
                    let a = RealRugStrictFinite::<PRECISION>::try_from_f64(6.).unwrap();
                    let b = RealRugStrictFinite::<PRECISION>::try_from_f64(2.).unwrap();
                    let c_expected = RealRugStrictFinite::<PRECISION>::try_from_f64(3.).unwrap();

                    test_div(a, b, c_expected);
                }

                #[test]
                fn neg_assign() {
                    test_neg_assign_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn add_assign() {
                    test_add_assign_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn sub_assign() {
                    test_sub_assign_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn mul_assign() {
                    test_mul_assign_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn div_assign() {
                    test_div_assign_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn mul_add_ref() {
                    test_mul_add_ref_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn abs() {
                    test_abs_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn acos() {
                    {
                        let a = RealRugStrictFinite::<53>::zero();
                        let pi_over_2 = RealRugStrictFinite::<53>::acos(a);
                        let expected = rug::Float::with_val(53, std::f64::consts::FRAC_PI_2);
                        assert_eq!(pi_over_2.as_ref(), &expected);
                    }
                    {
                        let a = RealRugStrictFinite::<100>::zero();
                        let pi_over_2 = RealRugStrictFinite::<100>::acos(a);
                        let expected = rug::Float::with_val(
                            100,
                            rug::Float::parse("1.5707963267948966192313216916397").unwrap(),
                        );
                        assert_eq!(pi_over_2.as_ref(), &expected);
                    }
                }

                #[test]
                fn asin() {
                    {
                        let a = RealRugStrictFinite::<53>::one();
                        let pi_over_2 = RealRugStrictFinite::<53>::asin(a);
                        let expected = rug::Float::with_val(53, std::f64::consts::FRAC_PI_2);
                        assert_eq!(pi_over_2.as_ref(), &expected);
                    }
                    {
                        let a = RealRugStrictFinite::<100>::one();
                        let pi_over_2 = RealRugStrictFinite::<100>::asin(a);
                        let expected = rug::Float::with_val(
                            100,
                            rug::Float::parse("1.5707963267948966192313216916397").unwrap(),
                        );
                        assert_eq!(pi_over_2.as_ref(), &expected);
                    }
                }

                #[test]
                fn cos() {
                    test_cos_real::<RealRugStrictFinite<64>>();
                    test_cos_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn sin() {
                    test_sin_real::<RealRugStrictFinite<64>>();
                    test_sin_real::<RealRugStrictFinite<PRECISION>>();
                }

                #[test]
                fn dot_product() {
                    let a = &[
                        RealRugStrictFinite::<100>::one(),
                        RealRugStrictFinite::<100>::try_from_f64(2.).unwrap(),
                    ];

                    let b = &[
                        RealRugStrictFinite::<100>::try_from_f64(2.).unwrap(),
                        RealRugStrictFinite::<100>::try_from_f64(-1.).unwrap(),
                    ];

                    let a: Vec<_> = a.iter().map(|a_i| a_i.as_ref()).collect();
                    let b: Vec<_> = b.iter().map(|b_i| b_i.as_ref()).collect();

                    let value = RealRugStrictFinite::<100>::try_new(
                        rug::Float::dot(a.into_iter().zip(b)).complete(100),
                    )
                    .unwrap();

                    assert_eq!(value.as_ref(), &rug::Float::with_val(100, 0.));
                }
                #[test]
                fn test_acos() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().acos();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().acos()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_acosh() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 1.5))
                            .unwrap();
                    let result = value.clone().acosh();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().acosh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_asin() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().asin();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().asin()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_asinh() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().asinh();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().asinh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_atan() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().atan();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().atan()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_atanh() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().atanh();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().atanh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_cos_02() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().cos();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().cos()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_cosh() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().cosh();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().cosh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_exp() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().exp();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().exp()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_is_finite() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    assert!(value.is_finite());

                    let value = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        f64::INFINITY,
                    ));
                    assert!(value.is_err());
                }

                #[test]
                fn test_is_infinite() {
                    let value = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        f64::INFINITY,
                    ));
                    assert!(value.is_err());

                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    assert!(!value.is_infinite());
                }

                #[test]
                fn test_ln() {
                    let value = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        std::f64::consts::E,
                    ))
                    .unwrap();
                    let result = value.clone().ln();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().ln()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_log10() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 10.0))
                            .unwrap();
                    let result = value.clone().log10();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().log10()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_log2() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 8.0))
                            .unwrap();
                    let result = value.clone().log2();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().log2()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_recip_02() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 2.0))
                            .unwrap();
                    let result = value.clone().try_reciprocal().unwrap();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().recip()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_sin_02() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().sin();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().sin()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_sinh() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().sinh();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().sinh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn sqrt() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                            .unwrap();
                    let result = value.clone().sqrt();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().sqrt()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn try_sqrt() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                            .unwrap();
                    let result = value.clone().try_sqrt().unwrap();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().sqrt()
                        ))
                        .unwrap()
                    );

                    assert!(
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -4.0))
                            .unwrap()
                            .try_sqrt()
                            .is_err()
                    )
                }

                #[test]
                fn test_tan() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().tan();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().tan()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_tanh() {
                    let value =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                            .unwrap();
                    let result = value.clone().tanh();
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                            PRECISION,
                            value.into_inner().tanh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_mul_add() {
                    let a =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 2.0))
                            .unwrap();
                    let b =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                            .unwrap();
                    let c =
                        RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                            .unwrap();
                    let result = a.clone().mul_add_ref(&b, &c);
                    assert_eq!(
                        result,
                        RealRugStrictFinite::<PRECISION>::try_new(
                            a.into_inner() * b.as_ref() + c.as_ref()
                        )
                        .unwrap()
                    );
                }
            }

            mod complex {
                use super::*;
                //use rug::Complex;
                use rug::Float;

                #[test]
                fn add() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 2.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 4.))
                        .unwrap();
                    let c_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(4., 6.))
                            .unwrap();
                    test_add(a, b, c_expected);
                }

                #[test]
                fn sub() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 2.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 4.))
                        .unwrap();
                    let c_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(2., -2.))
                            .unwrap();
                    test_sub(a, b, c_expected);
                }

                #[test]
                fn mul() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 2.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 4.))
                        .unwrap();
                    let c_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-5., 14.))
                            .unwrap();
                    test_mul(a, b, c_expected);
                }

                #[test]
                fn div() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-5., 14.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 4.))
                        .unwrap();
                    let c_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 2.))
                            .unwrap();
                    test_div(a, b, c_expected);
                }

                #[test]
                fn add_assign() {
                    let mut a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 2.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 4.))
                        .unwrap();

                    a += &b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(4., 6.))
                            .unwrap();
                    assert_eq!(a, a_expected);

                    a += b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(7., 10.))
                            .unwrap();
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn sub_assign() {
                    let mut a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 2.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(2., 4.))
                        .unwrap();

                    a -= &b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., -2.))
                            .unwrap();
                    assert_eq!(a, a_expected);

                    a -= b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-1., -6.))
                            .unwrap();
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn mul_assign() {
                    let mut a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 2.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(2., 4.))
                        .unwrap();

                    a *= &b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-2., 16.))
                            .unwrap();
                    assert_eq!(a, a_expected);

                    a *= b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-68., 24.))
                            .unwrap();
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn div_assign() {
                    let mut a =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-68., 24.))
                            .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(2., 4.))
                        .unwrap();

                    a /= &b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-2., 16.))
                            .unwrap();
                    assert_eq!(a, a_expected);

                    a /= b;
                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 2.))
                            .unwrap();
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn from_f64() {
                    let v_100bits =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(16.25, 2.))
                            .unwrap();
                    assert_eq!(
                        ComplexRugStrictFinite::<PRECISION>::real_part(&v_100bits),
                        16.25
                    );
                    assert_eq!(
                        ComplexRugStrictFinite::<PRECISION>::imag_part(&v_100bits),
                        2.
                    );

                    let v_53bits =
                        ComplexRugStrictFinite::<53>::try_from(Complex::new(16.25, 2.)).unwrap();
                    assert_eq!(ComplexRugStrictFinite::<53>::real_part(&v_53bits), 16.25);
                    assert_eq!(ComplexRugStrictFinite::<53>::imag_part(&v_53bits), 2.);

                    // 16.25 can be exactly represented in f64 and thus at precision >= 53
                    let v_53bits_2 =
                        ComplexRugStrictFinite::<53>::try_from(Complex::new(16.25, 2.)).unwrap();
                    assert_eq!(ComplexRugStrictFinite::<53>::real_part(&v_53bits_2), 16.25);
                    assert_eq!(ComplexRugStrictFinite::<53>::imag_part(&v_53bits_2), 2.);
                }

                #[test]
                #[should_panic]
                fn from_f64_failing() {
                    // this should fail because f64 requires precision >= 53
                    let _v_52bits =
                        ComplexRugStrictFinite::<52>::try_from(Complex::new(16.25, 2.)).unwrap();
                }

                #[test]
                fn conj() {
                    let v = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(16.25, 2.))
                        .unwrap();

                    let v_conj = ComplexRugStrictFinite::<PRECISION>::conjugate(v);
                    assert_eq!(
                        ComplexRugStrictFinite::<PRECISION>::real_part(&v_conj),
                        16.25
                    );
                    assert_eq!(ComplexRugStrictFinite::<PRECISION>::imag_part(&v_conj), -2.);
                }

                #[test]
                fn neg_assign() {
                    let mut a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 2.))
                        .unwrap();
                    a.neg_assign();

                    let a_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-1., -2.))
                            .unwrap();
                    assert_eq!(a, a_expected);
                }

                #[test]
                fn abs() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-3., 4.))
                        .unwrap();

                    let abs = a.abs();
                    let abs_expected = RealRugStrictFinite::<100>::try_from_f64(5.).unwrap();
                    assert_eq!(abs, abs_expected);
                }

                #[test]
                fn mul_add_ref() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(2., -3.))
                        .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 1.))
                        .unwrap();
                    let c = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., -4.))
                        .unwrap();

                    let d_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(10., -11.))
                            .unwrap();

                    let d = a.mul_add_ref(&b, &c);
                    assert_eq!(d, d_expected);
                }

                #[test]
                fn mul_complex_with_real() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 2.))
                        .unwrap();
                    let b = RealRugStrictFinite::<100>::try_from_f64(3.).unwrap();

                    let a_times_b_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 6.))
                            .unwrap();

                    test_mul_complex_with_real(a, b, a_times_b_expected);
                }

                #[test]
                fn mul_assign_complex_with_real() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 2.))
                        .unwrap();
                    let b = RealRugStrictFinite::<100>::try_from_f64(3.).unwrap();

                    let a_times_b_expected =
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(3., 6.))
                            .unwrap();

                    test_mul_assign_complex_with_real(a, b, a_times_b_expected);
                }

                #[test]
                fn dot_product() {
                    let a = &[
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(1., 3.))
                            .unwrap(),
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(2., 4.))
                            .unwrap(),
                    ];

                    let b = &[
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-2., -5.))
                            .unwrap(),
                        ComplexRugStrictFinite::<PRECISION>::try_from(Complex::new(-1., 6.))
                            .unwrap(),
                    ];

                    let a: Vec<_> = a.iter().map(|a_i| a_i.as_ref()).collect();
                    let b: Vec<_> = b.iter().map(|b_i| b_i.as_ref()).collect();

                    // computes a * a^T
                    let a_times_a = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::dot(a.clone().into_iter().zip(a.clone()))
                            .complete((100, 100)),
                    )
                    .unwrap();
                    assert_eq!(
                        a_times_a.as_ref(),
                        &rug::Complex::with_val(100, (-20., 22.))
                    );

                    // computes a * b^T
                    let a_times_b = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::dot(a.clone().into_iter().zip(b.clone()))
                            .complete((100, 100)),
                    )
                    .unwrap();
                    assert_eq!(
                        a_times_b.as_ref(),
                        &rug::Complex::with_val(100, (-13., -3.))
                    );

                    // computes b * a^T
                    let b_times_a = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::dot(b.into_iter().zip(a)).complete((100, 100)),
                    )
                    .unwrap();
                    assert_eq!(
                        b_times_a.as_ref(),
                        &rug::Complex::with_val(100, (-13., -3.))
                    );
                }

                #[test]
                fn test_acos() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().acos();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().acos()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_acosh() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (1.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().acosh();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().acosh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_asin() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().asin();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().asin()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_asinh() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().asinh();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().asinh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_atan() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().atan();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().atan()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_atanh() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().atanh();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().atanh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_cos_01() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().cos();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().cos()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_cosh() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().cosh();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().cosh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_exp() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().exp();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().exp()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_is_finite() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    assert!(value.is_finite());

                    let value =
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            100,
                            (Float::with_val(PRECISION, f64::INFINITY), 0.5),
                        ));
                    assert!(value.is_err());
                }

                #[test]
                fn test_is_infinite() {
                    let value =
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            100,
                            (Float::with_val(PRECISION, f64::INFINITY), 0.5),
                        ));
                    assert!(value.is_err());

                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    assert!(!value.is_infinite());
                }

                #[test]
                fn test_ln() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (std::f64::consts::E, 1.0)),
                    )
                    .unwrap();
                    let result = value.clone().ln();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().ln()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_log10() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (10.0, 1.0)),
                    )
                    .unwrap();
                    let result = value.clone().log10();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().log10()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_log2() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (8.0, 1.0)),
                    )
                    .unwrap();
                    let result = value.clone().log2();
                    println!("result = {result:?}");
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().ln() / rug::Float::with_val(PRECISION, 2.).ln()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_recip() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (2.0, 0.0)),
                    )
                    .unwrap();
                    let result = value.clone().try_reciprocal().unwrap();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().recip()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_sin_01() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().sin();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().sin()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_sinh() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().sinh();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().sinh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn sqrt() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (4.0, 1.0)),
                    )
                    .unwrap();
                    let result = value.clone().sqrt();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().sqrt()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn try_sqrt() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (4.0, 1.0)),
                    )
                    .unwrap();
                    let result = value.clone().try_sqrt().unwrap();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().sqrt()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_tan() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().tan();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().tan()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_tanh() {
                    let value = ComplexRugStrictFinite::<PRECISION>::try_new(
                        rug::Complex::with_val(PRECISION, (0.5, 0.5)),
                    )
                    .unwrap();
                    let result = value.clone().tanh();
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            value.into_inner().tanh()
                        ))
                        .unwrap()
                    );
                }

                #[test]
                fn test_mul_add() {
                    let a = ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                        PRECISION,
                        (2.0, 1.0),
                    ))
                    .unwrap();
                    let b = ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                        PRECISION,
                        (3.0, 1.0),
                    ))
                    .unwrap();
                    let c = ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                        PRECISION,
                        (4.0, 1.0),
                    ))
                    .unwrap();
                    let result = a.clone().mul_add_ref(&b, &c);
                    assert_eq!(
                        result,
                        ComplexRugStrictFinite::<PRECISION>::try_new(rug::Complex::with_val(
                            PRECISION,
                            a.as_ref() * b.as_ref() + c.as_ref()
                        ))
                        .unwrap()
                    );
                }
            }
        }
    }

    mod functions_real_type {
        use super::*;

        mod native64 {

            use super::*;

            #[test]
            fn test_atan2() {
                let a: f64 = 27.0;
                let b: f64 = 13.0;

                let result = a.atan2(b);
                assert_eq!(result, a.atan2(b));
            }

            #[test]
            fn test_ceil() {
                let value: f64 = 3.7;
                let result = value.kernel_ceil();
                assert_eq!(result, value.ceil());
            }

            #[test]
            fn test_clamp() {
                let value: f64 = 5.0;
                let min: f64 = 3.0;
                let max: f64 = 7.0;
                let result = Clamp::clamp_ref(value, &min, &max);
                assert_eq!(result, f64::clamp(value, min, max));
            }

            #[test]
            fn test_classify() {
                let value: f64 = 3.7;
                let result = Classify::classify(&value);
                assert_eq!(result, f64::classify(value));
            }

            #[test]
            fn test_copysign() {
                let value: f64 = 3.5;
                let sign: f64 = -1.0;
                let result = value.kernel_copysign(&sign);
                assert_eq!(result, value.copysign(sign));
            }

            #[test]
            fn test_epsilon() {
                let eps = f64::epsilon();
                assert_eq!(eps, f64::EPSILON);
            }

            #[test]
            fn test_exp_m1() {
                let value: f64 = 0.5;
                let result = ExpM1::exp_m1(value);
                assert_eq!(result, f64::exp_m1(value));
            }

            #[test]
            fn test_floor() {
                let value: f64 = 3.7;
                let result = value.kernel_floor();
                assert_eq!(result, value.floor());
            }

            #[test]
            fn test_fract() {
                let value: f64 = 3.7;
                let result = value.kernel_fract();
                assert_eq!(result, value.fract());
            }

            #[test]
            fn test_hypot() {
                let a: f64 = 3.0;
                let b: f64 = 4.0;
                let result = Hypot::hypot(a, &b);
                assert_eq!(result, f64::hypot(a, b));
            }

            #[test]
            fn test_is_sign_negative() {
                let value: f64 = -1.0;
                assert!(value.kernel_is_sign_negative());

                let value: f64 = -0.0;
                assert!(value.kernel_is_sign_negative());

                let value: f64 = 0.0;
                assert!(!value.kernel_is_sign_negative());

                let value: f64 = 1.0;
                assert!(!value.kernel_is_sign_negative());
            }

            #[test]
            fn test_is_sign_positive() {
                let value: f64 = -1.0;
                assert!(!value.kernel_is_sign_positive());

                let value: f64 = -0.0;
                assert!(!value.kernel_is_sign_positive());

                let value: f64 = 0.0;
                assert!(value.kernel_is_sign_positive());

                let value: f64 = 1.0;
                assert!(value.kernel_is_sign_positive());
            }

            #[test]
            fn test_ln_1p() {
                let value: f64 = 0.5;
                let result = Ln1p::ln_1p(value);
                assert_eq!(result, f64::ln_1p(value));
            }

            #[test]
            fn test_max() {
                let a: f64 = 3.0;
                let b: f64 = 4.0;
                let result = a.max(b);
                assert_eq!(result, a.max(b));
            }

            #[test]
            fn test_min() {
                let a: f64 = 3.0;
                let b: f64 = 4.0;
                let result = a.min(b);
                assert_eq!(result, a.min(b));
            }

            #[test]
            fn max_finite() {
                let max = f64::max_finite();
                assert_eq!(max, f64::MAX);
            }

            #[test]
            fn min_finite() {
                let min = f64::min_finite();
                assert_eq!(min, f64::MIN);
            }

            #[test]
            fn test_mul_add_mul_mut() {
                let mut a: f64 = 2.0;
                let b: f64 = 3.0;
                let c: f64 = 4.0;
                let d: f64 = -1.0;
                let mut result = a;
                result.kernel_mul_add_mul_mut(&b, &c, &d);

                a.mul_add_assign(b, c * d);
                assert_eq!(result, a);
            }

            #[test]
            fn test_mul_sub_mul_mut() {
                let mut a: f64 = 2.0;
                let b: f64 = 3.0;
                let c: f64 = 4.0;
                let d: f64 = -1.0;
                let mut result = a;
                result.kernel_mul_sub_mul_mut(&b, &c, &d);

                a.mul_add_assign(b, -c * d);
                assert_eq!(result, a);
            }

            #[test]
            fn test_negative_one() {
                let value = f64::negative_one();
                assert_eq!(value, -1.0);
            }

            #[test]
            fn test_one() {
                let value = f64::one();
                assert_eq!(value, 1.0);
            }

            #[test]
            fn test_round() {
                let value: f64 = 3.5;
                let result = value.kernel_round();
                assert_eq!(result, value.round());
            }

            #[test]
            fn test_round_ties_even() {
                let value: f64 = 3.5;
                let result = value.kernel_round_ties_even();
                assert_eq!(result, value.round_ties_even());
            }

            #[test]
            fn test_signum() {
                let value: f64 = -3.5;
                let result = value.kernel_signum();
                assert_eq!(result, value.signum());
            }

            #[test]
            fn test_total_cmp() {
                let a: f64 = 3.0;
                let b: f64 = 4.0;
                let result = a.total_cmp(&b);
                assert_eq!(result, a.total_cmp(&b));
            }

            #[test]
            fn test_try_from_64() {
                let result = f64::try_from_f64(3.7);
                assert!(result.is_ok());
            }

            #[test]
            fn test_try_from_64_error_infinite() {
                let result = f64::try_from_f64(f64::INFINITY);
                assert!(result.is_err());
            }

            #[test]
            fn test_try_from_64_error_nan() {
                let result = f64::try_from_f64(f64::NAN);
                assert!(result.is_err());
            }

            #[test]
            fn test_trunc() {
                let value: f64 = 3.7;
                let result = value.kernel_trunc();
                assert_eq!(result, value.trunc());
            }

            #[test]
            fn test_two() {
                let value = f64::two();
                assert_eq!(value, 2.0);
            }
        }

        #[cfg(feature = "rug")]
        mod rug100 {
            use super::*;
            use crate::backends::rug::validated::RealRugStrictFinite;
            use rug::{Float, ops::CompleteRound};
            use try_create::{IntoInner, TryNew};

            const PRECISION: u32 = 100;

            #[test]
            fn from_f64() {
                let v_100bits = RealRugStrictFinite::<100>::try_from_f64(16.25).unwrap();

                assert_eq!(v_100bits, 16.25);

                let v_53bits = RealRugStrictFinite::<53>::try_from_f64(16.25).unwrap();
                assert_eq!(v_53bits, 16.25);

                // 16.25 can be exactly represented in f64 and thus at precision >= 53
                let v_53bits_2 = RealRugStrictFinite::<53>::try_from_f64(16.25).unwrap();
                assert_eq!(v_53bits_2, 16.25);
            }

            #[test]
            #[should_panic]
            fn from_f64_failing() {
                // this should fail because f64 requires precision >= 53
                let _v_52bits = RealRugStrictFinite::<52>::try_from_f64(16.25).unwrap();
            }

            #[test]
            fn max_finite() {
                let max = RealRugStrictFinite::<53>::max_finite();
                assert_eq!(
                    max.as_ref(),
                    &rug::Float::with_val(
                        53,
                        rug::Float::parse("1.0492893582336937e323228496").unwrap()
                    )
                );
            }

            #[test]
            fn min_finite() {
                let min = RealRugStrictFinite::<53>::min_finite();
                assert_eq!(
                    min.as_ref(),
                    &rug::Float::with_val(
                        53,
                        rug::Float::parse("-1.0492893582336937e323228496").unwrap()
                    )
                );
            }

            #[test]
            fn test_atan2() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 27.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 13.0))
                    .unwrap();
                let result = a.clone().atan2(&b);
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        a.into_inner().atan2(b.as_ref())
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_ceil() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.7))
                        .unwrap();
                let result = value.clone().kernel_ceil();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().ceil()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_clamp() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 5.0))
                        .unwrap();
                let min =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                        .unwrap();
                let max =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 7.0))
                        .unwrap();
                let result = value.clone().clamp_ref(&min, &max);
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().clamp_ref(min.as_ref(), max.as_ref())
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_classify() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.7))
                        .unwrap();
                let result = value.classify();
                assert_eq!(result, value.into_inner().classify());
            }

            #[test]
            fn test_copysign() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.5))
                        .unwrap();
                let sign =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -1.0))
                        .unwrap();
                let result = value.clone().kernel_copysign(&sign);
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().copysign(sign.as_ref())
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_epsilon() {
                let rug_eps = rug::Float::u_pow_u(2, PRECISION - 1)
                    .complete(PRECISION)
                    .recip();
                //println!("eps: {}", rug_eps);

                let eps = RealRugStrictFinite::<PRECISION>::epsilon();
                assert_eq!(
                    eps,
                    RealRugStrictFinite::<PRECISION>::try_new(rug_eps.clone()).unwrap()
                );

                // here we compute new_eps as the difference between 1 and the next larger floating point number
                let mut new_eps = Float::with_val(PRECISION, 1.);
                new_eps.next_up();
                new_eps -= Float::with_val(PRECISION, 1.);
                assert_eq!(new_eps, rug_eps.clone());

                //println!("new_eps: {new_eps}");

                let one = RealRugStrictFinite::<PRECISION>::one();
                let result = RealRugStrictFinite::<PRECISION>::try_new(
                    new_eps / Float::with_val(PRECISION, 2.),
                )
                .unwrap()
                    + &one;
                assert_eq!(result, one);
            }

            #[test]
            fn test_exp_m1() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                        .unwrap();
                let result = value.clone().exp_m1();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().exp_m1()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_floor() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.7))
                        .unwrap();
                let result = value.clone().kernel_floor();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().floor()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_fract() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.7))
                        .unwrap();
                let result = value.clone().kernel_fract();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().fract()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_hypot() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                    .unwrap();
                let result = a.clone().hypot(&b);
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        a.into_inner().hypot(b.as_ref())
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_is_sign_negative() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -1.0))
                        .unwrap();
                assert!(value.kernel_is_sign_negative());

                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -0.0))
                        .unwrap();
                assert!(value.kernel_is_sign_negative());

                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.0))
                        .unwrap();
                assert!(!value.kernel_is_sign_negative());

                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 1.0))
                        .unwrap();
                assert!(!value.kernel_is_sign_negative());
            }

            #[test]
            fn test_is_sign_positive() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -1.0))
                        .unwrap();
                assert!(!value.kernel_is_sign_positive());

                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -0.0))
                        .unwrap();
                assert!(!value.kernel_is_sign_positive());

                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.0))
                        .unwrap();
                assert!(value.kernel_is_sign_positive());

                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 1.0))
                        .unwrap();
                assert!(value.kernel_is_sign_positive());
            }

            #[test]
            fn test_ln_1p() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 0.5))
                        .unwrap();
                let result = value.clone().ln_1p();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().ln_1p()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_max() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                    .unwrap();
                let result = a.max_by_ref(&b);
                assert_eq!(
                    result,
                    &RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        a.clone().into_inner().max(b.as_ref())
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_min() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                    .unwrap();
                let result = a.min_by_ref(&b);
                assert_eq!(
                    result,
                    &RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        a.clone().into_inner().min(b.as_ref())
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_mul_add_mul_mut() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 2.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                    .unwrap();
                let c = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                    .unwrap();
                let d = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -1.0))
                    .unwrap();
                let mut result = a.clone();
                result.kernel_mul_add_mul_mut(&b, &c, &d);
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        a.into_inner()
                            .mul_add_ref(b.as_ref(), &(c.into_inner() * d.as_ref()))
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_mul_sub_mul_mut() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 2.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                    .unwrap();
                let c = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                    .unwrap();
                let d = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -1.0))
                    .unwrap();
                let mut result = a.clone();
                result.kernel_mul_sub_mul_mut(&b, &c, &d);
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        a.into_inner()
                            .mul_add_ref(b.as_ref(), &(-c.into_inner() * d.as_ref()))
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_negative_one() {
                let value = RealRugStrictFinite::<PRECISION>::negative_one();
                assert_eq!(
                    value,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -1.0))
                        .unwrap()
                );
            }

            #[test]
            fn test_one() {
                let value = RealRugStrictFinite::<PRECISION>::one();
                assert_eq!(
                    value,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 1.0))
                        .unwrap()
                );
            }

            #[test]
            fn test_round() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.5))
                        .unwrap();
                let result = value.clone().kernel_round();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().round()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_round_ties_even() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.5))
                        .unwrap();
                let result = value.clone().kernel_round_ties_even();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().round_even()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_signum() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, -3.5))
                        .unwrap();
                let result = value.clone().kernel_signum();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().signum()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_total_cmp() {
                let a = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.0))
                    .unwrap();
                let b = RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 4.0))
                    .unwrap();
                let result = a.total_cmp(&b);
                assert_eq!(result, a.into_inner().total_cmp(b.as_ref()));
            }

            #[test]
            fn test_try_from_64() {
                let result = RealRugStrictFinite::<PRECISION>::try_from_f64(3.7);
                assert!(result.is_ok());
            }

            #[test]
            fn test_try_from_64_error_infinite() {
                let result = RealRugStrictFinite::<PRECISION>::try_from_f64(f64::INFINITY);
                assert!(result.is_err());
            }

            #[test]
            fn test_try_from_64_error_nan() {
                let result = RealRugStrictFinite::<PRECISION>::try_from_f64(f64::NAN);
                assert!(result.is_err());
            }

            #[test]
            fn test_trunc() {
                let value =
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 3.7))
                        .unwrap();
                let result = value.clone().kernel_trunc();
                assert_eq!(
                    result,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(
                        PRECISION,
                        value.into_inner().trunc()
                    ))
                    .unwrap()
                );
            }

            #[test]
            fn test_two() {
                let value = RealRugStrictFinite::<PRECISION>::two();
                assert_eq!(
                    value,
                    RealRugStrictFinite::<PRECISION>::try_new(Float::with_val(PRECISION, 2.0))
                        .unwrap()
                );
            }
        }
    }

    mod util_funcs {
        use crate::{
            backends::native64::validated::RealNative64StrictFinite, new_random_vec,
            try_vec_f64_into_vec_real,
        };
        use rand::{SeedableRng, distr::Uniform, rngs::StdRng};

        #[test]
        fn test_new_random_vec_deterministic() {
            let seed = [42; 32];
            let mut rng1 = StdRng::from_seed(seed);
            let mut rng2 = StdRng::from_seed(seed);
            let uniform = Uniform::new(-1.0, 1.0).unwrap();

            let vec1: Vec<f64> = new_random_vec(10, &uniform, &mut rng1);
            let vec2: Vec<RealNative64StrictFinite> = new_random_vec(10, &uniform, &mut rng2);

            assert_eq!(vec1.len(), 10);
            assert_eq!(vec2.len(), 10);
            for i in 0..10 {
                assert_eq!(&vec1[i], vec2[i].as_ref());
            }
        }

        #[test]
        fn test_try_vec_f64_into_vec_real_success() {
            let input = vec![1.0, -2.5, 1e10];
            let result = try_vec_f64_into_vec_real::<RealNative64StrictFinite>(input);
            assert!(result.is_ok());
            let output = result.unwrap();
            assert_eq!(output[0].as_ref(), &1.0);
            assert_eq!(output[1].as_ref(), &-2.5);
        }

        #[test]
        fn test_try_vec_f64_into_vec_real_fail() {
            let input = vec![1.0, f64::NAN, 3.0];
            let result = try_vec_f64_into_vec_real::<RealNative64StrictFinite>(input);
            assert!(result.is_err());
        }
    }
}