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
#![deny(rustdoc::broken_intra_doc_links)]

//! This module provides traits, error types, and implementations for various
//! trigonometric functions.
//!
//! It defines a set of traits (e.g., [`Sin`], [`Cos`], [`ATan2`]) for standard
//! trigonometric operations and their inverses. These traits are implemented
//! for [`f64`], [`num::Complex<f64>`], [`RealValidated`](crate::RealValidated), [`ComplexValidated`](crate::ComplexValidated)
//! and can be extended to other numeric types satisfying the [`RealScalar`](crate::RealScalar) or [`ComplexScalar`](crate::ComplexScalar) traits.
//!
//! A comprehensive error handling system is in place, utilizing specific input
//! error enums (e.g., [`ASinRealInputErrors`], [`ATanComplexInputErrors`]) and
//! general function error type aliases (e.g., [`SinErrors`], [`CosErrors`])
//! built upon the [`FunctionErrors`] struct. This allows for granular reporting
//! of issues such as invalid arguments (NaN, infinity), out-of-domain values,
//! or poles.
//!
//! The design emphasizes robustness through strict validation of inputs and outputs,
//! primarily using the [`StrictFinitePolicy`].

use crate::{
    core::{errors::capture_backtrace, policies::StrictFinitePolicy},
    functions::FunctionErrors,
    kernels::{RawComplexTrait, RawRealTrait, RawScalarTrait},
};
use duplicate::duplicate_item;
use num::Complex;
use std::backtrace::Backtrace;
use thiserror::Error;
use try_create::ValidationPolicy;

//------------------------------------------------------------------------------------------------
// Real and Complex Number Input Errors (for functions like sin, cos)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    enum_name             enum_doc;
    [CosInputErrors]  ["Errors that can occur during the input validation phase when computing the *cosine* of a real or complex number.\n\nThis enum is used as a source for the `Input` variant of [`CosErrors`].\n\n# Type Parameters\n\n- `RawScalar`: A type that implements the [`RawScalarTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `RawScalar::ValidationErrors` (e.g., [`crate::core::errors::ErrorsValidationRawReal`], [`crate::core::errors::ErrorsValidationRawComplex`], etc.).\n\n# Variants\n\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., NaN, Infinity). The `source` field provides the specific raw validation error."];
    [SinInputErrors]  ["Errors that can occur during the input validation phase when computing the *sine* of a real or complex number.\n\nThis enum is used as a source for the `Input` variant of [`SinErrors`].\n\n# Type Parameters\n\n- `RawScalar`: A type that implements the [`RawScalarTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `RawScalar::ValidationErrors` (e.g., [`crate::core::errors::ErrorsValidationRawReal`], [`crate::core::errors::ErrorsValidationRawComplex`], etc.).\n\n# Variants\n\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., NaN, Infinity). The `source` field provides the specific raw validation error."];
)]
#[derive(Debug, Error)]
#[doc = enum_doc]
pub enum enum_name<RawScalar: RawScalarTrait> {
    /// The argument of the function is invalid.
    ///
    /// This variant indicates that the argument failed general validation checks
    /// according to the chosen validation policy (e.g., NaN, Infinity).
    #[error("the argument of the function is invalid!")]
    InvalidArgument {
        /// The underlying validation error from the input's raw scalar type.
        #[source]
        #[backtrace]
        source: RawScalar::ValidationErrors,
    },
}

//------------------------------------------------------------------------------------------------
// Real Number Input Errors (for functions like tan, atan)
//------------------------------------------------------------------------------------------------

/// Errors that can occur during the input validation phase when computing the *tangent* of a *real number*.
///
/// This enum is used as a source for the `Input` variant of [`TanRealErrors`].
///
/// # Type Parameters
///
/// - `RawReal`: A type that implements the [`RawRealTrait`] trait.
///
/// # Variants
///
/// - `ArgumentIsPole`: Indicates the input argument is a mathematical pole (e.g., π/2 + kπ).
/// - `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., NaN, Infinity).
#[derive(Debug, Error)]
pub enum TanRealInputErrors<RawReal: RawRealTrait> {
    /// The argument of the function is a mathematical pole (e.g., π/2 + kπ).
    #[error("the argument ({value}) is a mathematical pole for the tangent function!")]
    ArgumentIsPole {
        /// The value that is a pole.
        value: RawReal,
        /// The backtrace of the error.
        backtrace: Backtrace,
    },

    /// The argument of the function is invalid.
    ///
    /// This variant indicates that the argument failed general validation checks
    /// according to the chosen validation policy (e.g., NaN, Infinity).
    #[error("the argument of the function is invalid!")]
    InvalidArgument {
        /// The underlying validation error from the input's raw real type.
        #[source]
        #[backtrace]
        source: <RawReal as RawScalarTrait>::ValidationErrors,
    },
}

/// Errors that can occur during the input validation phase when computing the *inverse tangent* of a *real number*.
///
/// This enum is used as a source for the `Input` variant of [`ATanRealErrors`].
///
/// # Type Parameters
///
/// - `RawReal`: A type that implements the [`RawRealTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `<RawReal as RawScalarTrait>::ValidationErrors` (e.g., [`crate::core::errors::ErrorsValidationRawReal<f64>`]).
///
/// # Variants
/// - `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., NaN, Infinity). The `source` field provides the specific raw validation error.
#[derive(Debug, Error)]
pub enum ATanRealInputErrors<RawReal: RawRealTrait> {
    /// The argument of the function is invalid.
    ///
    /// This variant indicates that the argument failed general validation checks
    /// according to the chosen validation policy (e.g., NaN, Infinity).
    #[error("the argument of the function is invalid!")]
    InvalidArgument {
        /// The underlying validation error from the input's raw real type.
        #[source]
        #[backtrace]
        source: RawReal::ValidationErrors,
    },
}

//------------------------------------------------------------------------------------------------
// Real Number Input Errors (for functions like asin, acos with domain constraints)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    enum_name             enum_doc;
    [ASinRealInputErrors] ["Errors that can occur during the input validation phase when computing the *inverse sine* of a *real number*.\n\nThis enum is used as a source for the `Input` variant of [`ASinRealErrors`].\n\n# Type Parameters\n\n- `RawReal`: A type that implements the [`RawRealTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `<RawReal as RawScalarTrait>::ValidationErrors` (e.g., [`crate::core::errors::ErrorsValidationRawReal<f64>`]).\n\n# Variants\n\n- `OutOfDomain`: Indicates the input argument is outside the valid domain `[-1, 1]`.\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., NaN, Infinity). The `source` field provides the specific raw validation error."];
    [ACosRealInputErrors] ["Errors that can occur during the input validation phase when computing the *inverse cosine* of a *real number*.\n\nThis enum is used as a source for the `Input` variant of [`ACosRealErrors`].\n\n# Type Parameters\n\n- `RawReal`: A type that implements the [`RawRealTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `<RawReal as RawScalarTrait>::ValidationErrors` (e.g., [`crate::core::errors::ErrorsValidationRawReal<f64>`]).\n\n# Variants\n\n- `OutOfDomain`: Indicates the input argument is outside the valid domain `[-1, 1]`.\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., NaN, Infinity). The `source` field provides the specific raw validation error."];
)]
#[derive(Debug, Error)]
#[doc = enum_doc]
pub enum enum_name<RawReal: RawRealTrait> {
    /// The argument of the function is not in the valid domain `[-1, 1]`.
    #[error("the argument of the function ({value}) is not in the domain [-1.,1.]!")]
    OutOfDomain {
        /// The value that is out of the domain [-1.,1.].
        value: RawReal,

        /// The backtrace of the error.
        backtrace: Backtrace,
    },

    /// The argument of the function is invalid (e.g., NaN, Infinity, or subnormal).
    ///
    /// This variant indicates that the argument failed general validation checks
    /// according to the chosen validation policy (e.g., NaN, Infinity).
    #[error("the argument of the function is invalid!")]
    InvalidArgument {
        /// The source error that occurred during validation.
        #[source]
        #[backtrace]
        source: <RawReal as RawScalarTrait>::ValidationErrors,
    },
}

//------------------------------------------------------------------------------------------------
// Real and Complex Number General Function Errors (Type Aliases for FunctionErrors)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    enum_name   ErrIn            enum_doc;
    [CosErrors] [CosInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *cosine* computation on a real or complex number.\n\nRepresents failures from [`Cos::try_cos()`].\n\n# Type Parameters\n\n- `RawScalar`: Implements [`RawScalarTrait`]. Defines input error type via `ErrIn<RawScalar>` and output raw error via `RawScalar::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawScalar> }`: Input was invalid (e.g., NaN, Infinity).\n- `Output { source: RawScalar::ValidationErrors }`: Computed output was invalid (e.g., NaN, Infinity)."];
    [SinErrors] [SinInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *sine* computation on a real or complex number.\n\nRepresents failures from [`Sin::try_sin()`].\n\n# Type Parameters\n\n- `RawScalar`: Implements [`RawScalarTrait`]. Defines input error type via `ErrIn<RawScalar>` and output raw error via `RawScalar::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawScalar> }`: Input was invalid (e.g., NaN, Infinity).\n- `Output { source: RawScalar::ValidationErrors }`: Computed output was invalid (e.g., NaN, Infinity)."];
)]
#[doc = enum_doc]
pub type enum_name<RawScalar> =
    FunctionErrors<ErrIn<RawScalar>, <RawScalar as RawScalarTrait>::ValidationErrors>;

//------------------------------------------------------------------------------------------------
// Real Number General Function Errors (Type Aliases for FunctionErrors)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    enum_name        ErrIn                 enum_doc;
    [ACosRealErrors] [ACosRealInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *inverse cosine* computation on a *real number*.\n\nRepresents failures from [`ACos::try_acos()`].\n\n# Type Parameters\n\n- `RawReal`: Implements [`RawRealTrait`]. Defines input error type via `ErrIn<RawReal>` and output raw error via `<RawReal as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawReal> }`: Input was invalid (e.g., out of domain `[-1,1]`, NaN, Infinity).\n- `Output { source: <RawReal as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., NaN, Infinity)."];
    [ASinRealErrors] [ASinRealInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *inverse sine* computation on a *real number*.\n\nRepresents failures from [`ASin::try_asin()`].\n\n# Type Parameters\n\n- `RawReal`: Implements [`RawRealTrait`]. Defines input error type via `ErrIn<RawReal>` and output raw error via `<RawReal as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawReal> }`: Input was invalid (e.g., out of domain `[-1,1]`, NaN, Infinity).\n- `Output { source: <RawReal as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., NaN, Infinity)."];
    [ATanRealErrors] [ATanRealInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *inverse tangent* computation on a *real number*.\n\nRepresents failures from [`ATan::try_atan()`].\n\n# Type Parameters\n\n- `RawReal`: Implements [`RawRealTrait`]. Defines input error type via `ErrIn<RawReal>` and output raw error via `<RawReal as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawReal> }`: Input was invalid (e.g., NaN, Infinity).\n- `Output { source: <RawReal as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., NaN, Infinity)."];
    [TanRealErrors]  [TanRealInputErrors]  ["A type alias for [`FunctionErrors`], specialized for errors during *tangent* computation on a *real number*.\n\nRepresents failures from [`Tan::try_tan()`].\n\n# Type Parameters\n\n- `RawReal`: Implements [`RawRealTrait`]. Defines input error type via `ErrIn<RawReal>` and output raw error via `<RawReal as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawReal> }`: Input was invalid (e.g., NaN, Infinity).\n- `Output { source: <RawReal as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., NaN, Infinity)."];
)]
#[doc = enum_doc]
pub type enum_name<RawReal> =
    FunctionErrors<ErrIn<RawReal>, <RawReal as RawScalarTrait>::ValidationErrors>;

//------------------------------------------------------------------------------------------------
// Complex Number Input Errors (for functions like tan, asin, acos)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    enum_name                enum_doc;
    [ACosComplexInputErrors] ["Errors that can occur during the input validation phase when computing the *inverse cosine* of a *complex number*.\n\nThis enum is used as a source for the `Input` variant of [`ACosComplexErrors`].\n\n# Type Parameters\n\n- `RawComplex`: A type that implements the [`RawComplexTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., components are NaN, Infinity). The `source` field provides the specific raw validation error."];
    [ASinComplexInputErrors] ["Errors that can occur during the input validation phase when computing the *inverse sine* of a *complex number*.\n\nThis enum is used as a source for the `Input` variant of [`ASinComplexErrors`].\n\n# Type Parameters\n\n- `RawComplex`: A type that implements the [`RawComplexTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., components are NaN, Infinity). The `source` field provides the specific raw validation error."];
    [TanComplexInputErrors]  ["Errors that can occur during the input validation phase when computing the *tangent* of a *complex number*.\n\nThis enum is used as a source for the `Input` variant of [`TanComplexErrors`].\n\n# Type Parameters\n\n- `RawComplex`: A type that implements the [`RawComplexTrait`] trait. This type parameter is used to specify the numeric type for the computation and its associated raw error type `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `InvalidArgument`: Indicates that the input argument failed general validation checks (e.g., components are NaN, Infinity). The `source` field provides the specific raw validation error."];
)]
#[derive(Debug, Error)]
#[doc = enum_doc]
pub enum enum_name<RawComplex: RawComplexTrait> {
    /// The argument of the function is invalid (e.g., one or both components are NaN, Infinity, or subnormal).
    ///
    /// This variant indicates that the argument failed general validation checks
    /// according to the chosen validation policy.
    #[error("the argument of the function is invalid!")]
    InvalidArgument {
        /// The underlying validation error from the input's raw complex type.
        #[source]
        #[backtrace]
        source: <RawComplex as RawScalarTrait>::ValidationErrors,
    },
}

//------------------------------------------------------------------------------------------------
// Complex ATan Input Errors (Specific due to poles)
//------------------------------------------------------------------------------------------------
/// Errors that can occur during the input validation phase when attempting to compute
/// the arctangent of a complex number.
///
/// This enum is used as a source for the `Input` variant of [`ATanComplexErrors`].
/// It is generic over `RawComplex`, which must implement [`RawComplexTrait`].
/// This enum addresses failures in the initial validation of the input complex
/// number (e.g., components being NaN, Infinity, or subnormal) or if the
/// argument is a pole for the complex arctangent function (e.g., `0 +/- 1i`).
#[derive(Debug, Error)]
pub enum ATanComplexInputErrors<RawComplex: RawComplexTrait> {
    /// The input complex number is a pole for the arctangent function (e.g., `i` or `-i`).
    ///
    /// The complex arctangent function is undefined at these points.
    #[error("the argument ({value:?}) is a pole for the function!")]
    ArgumentIsPole {
        /// The argument value that is a pole.
        value: RawComplex,

        /// The backtrace of the error.
        backtrace: std::backtrace::Backtrace,
    },

    /// The argument of the function is invalid due to failing general validation checks.
    ///
    /// This variant indicates that the argument of the function is invalid w.r.t. the chosen validation policy (e.g. NaN, Infinity).
    /// It includes the source error that occurred during validation.
    #[error("the argument of the function is invalid!")]
    InvalidArgument {
        /// The source error that occurred during validation.
        #[source]
        #[backtrace]
        source: <RawComplex as RawScalarTrait>::ValidationErrors,
    },
}

//------------------------------------------------------------------------------------------------
// Complex Number General Function Errors (Type Aliases for FunctionErrors)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    enum_name           ErrIn                    enum_doc;
    [ACosComplexErrors] [ACosComplexInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *inverse cosine* computation on a *complex number*.\n\nRepresents failures from [`ACos::try_acos()`].\n\n# Type Parameters\n\n- `RawComplex`: Implements [`RawComplexTrait`]. Defines input error type via `ErrIn<RawComplex>` and output raw error via `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawComplex> }`: Input was invalid (e.g., components are NaN, Infinity).\n- `Output { source: <RawComplex as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., components are NaN, Infinity)."];
    [ASinComplexErrors] [ASinComplexInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *inverse sine* computation on a *complex number*.\n\nRepresents failures from [`ASin::try_asin()`].\n\n# Type Parameters\n\n- `RawComplex`: Implements [`RawComplexTrait`]. Defines input error type via `ErrIn<RawComplex>` and output raw error via `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawComplex> }`: Input was invalid (e.g., components are NaN, Infinity).\n- `Output { source: <RawComplex as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., components are NaN, Infinity)."];
    [TanComplexErrors]  [TanComplexInputErrors]  ["A type alias for [`FunctionErrors`], specialized for errors during *tangent* computation on a *complex number*.\n\nRepresents failures from [`Tan::try_tan()`].\n\n# Type Parameters\n\n- `RawComplex`: Implements [`RawComplexTrait`]. Defines input error type via `ErrIn<RawComplex>` and output raw error via `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawComplex> }`: Input was invalid (e.g., components are NaN, Infinity).\n- `Output { source: <RawComplex as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., components are NaN, Infinity)."];
    [ATanComplexErrors] [ATanComplexInputErrors] ["A type alias for [`FunctionErrors`], specialized for errors during *inverse tangent* computation on a *complex number*.\n\nRepresents failures from [`ATan::try_atan()`].\n\n# Type Parameters\n\n- `RawComplex`: Implements [`RawComplexTrait`]. Defines input error type via `ErrIn<RawComplex>` and output raw error via `<RawComplex as RawScalarTrait>::ValidationErrors`.\n\n# Variants\n\n- `Input { source: ErrIn<RawComplex> }`: Input was invalid (e.g., components are NaN, Infinity, or a pole like `0 +/- 1i`).\n- `Output { source: <RawComplex as RawScalarTrait>::ValidationErrors }`: Computed output was invalid (e.g., components are NaN, Infinity)."];
)]
#[doc = enum_doc]
pub type enum_name<RawComplex> =
    FunctionErrors<ErrIn<RawComplex>, <RawComplex as RawScalarTrait>::ValidationErrors>;

//------------------------------------------------------------------------------------------------
// Trigonometric Traits (Sin, Cos, Tan, ASin, ACos, ATan)
//------------------------------------------------------------------------------------------------
#[duplicate_item(
    T      try_func   func   trait_doc try_func_doc func_doc err_doc;
    [ACos] [try_acos] [acos] ["Trait for computing the *inverse cosine* of a number.\n\nThis trait defines methods for computing the *inverse cosine* of a number. Provides both a fallible method that returns a [`Result`] and a panicking method that directly returns the computed value or panics on invalid input.\n\n# Associated Types\n\n- `Error`: The error type that is returned by the `try_acos` method. This type must implement the [`std::error::Error`] trait.\n\n# Required Methods\n\n - `try_acos`: Computes the inverse cosine of the number and returns a [`Result`]. If the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n - `acos`: Computes the inverse cosine of the number and directly returns the computed value. In Debug mode this method may panic if the computation fails."]     ["Computes the *inverse cosine* of `self` and returns a [`Result`].\n\nIf the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n# Errors\n\nThis method returns an error if the computation fails. The error type is defined by the associated [`Error`] type."]  ["Computes and returns the *inverse cosine* of `self`.\n\nIn Debug mode this method may panic if the computation fails.\n\n# Panics\n\nIn Debug mode this method may panic if the computation fails. It is recommended to use the `try_acos` method for safe computations."]  ["The error type that is returned by the `try_acos` method."];
    [ASin] [try_asin] [asin] ["Trait for computing the *inverse sine* of a number.\n\nThis trait defines methods for computing the *inverse sine* of a number. Provides both a fallible method that returns a [`Result`] and a panicking method that directly returns the computed value or panics on invalid input.\n\n# Associated Types\n\n- `Error`: The error type that is returned by the `try_asin` method. This type must implement the [`std::error::Error`] trait.\n\n# Required Methods\n\n - `try_asin`: Computes the inverse sine of the number and returns a [`Result`]. If the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n - `asin`: Computes the inverse sine of the number and directly returns the computed value. In Debug mode this method may panic if the computation fails."]             ["Computes the *inverse sine* of `self` and returns a [`Result`].\n\nIf the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n# Errors\n\nThis method returns an error if the computation fails. The error type is defined by the associated [`Error`] type."]    ["Computes and returns the *inverse sine* of `self`.\n\nIn Debug mode this method may panic if the computation fails.\n\n# Panics\n\nIn Debug mode this method may panic if the computation fails. It is recommended to use the `try_asin` method for safe computations."]    ["The error type that is returned by the `try_asin` method."];
    [ATan] [try_atan] [atan] ["Trait for computing the *inverse tangent* of a number.\n\nThis trait defines methods for computing the *inverse tangent* of a number. Provides both a fallible method that returns a [`Result`] and a panicking method that directly returns the computed value or panics on invalid input.\n\n# Associated Types\n\n- `Error`: The error type that is returned by the `try_atan` method. This type must implement the [`std::error::Error`] trait.\n\n# Required Methods\n\n - `try_atan`: Computes the inverse tangent of the number and returns a [`Result`]. If the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n - `atan`: Computes the inverse tangent of the number and directly returns the computed value. In Debug mode this method may panic if the computation fails."] ["Computes the *inverse tangent* of `self` and returns a [`Result`].\n\nIf the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n# Errors\n\nThis method returns an error if the computation fails. The error type is defined by the associated [`Error`] type."] ["Computes and returns the *inverse tangent* of `self`.\n\nIn Debug mode this method may panic if the computation fails.\n\n# Panics\n\nIn Debug mode this method may panic if the computation fails. It is recommended to use the `try_atan` method for safe computations."] ["The error type that is returned by the `try_atan` method."];
    [Cos]  [try_cos]  [cos]  ["Trait for computing the *cosine* of a number.\n\nThis trait defines methods for computing the *cosine* of a number. Provides both a fallible method that returns a [`Result`] and a panicking method that directly returns the computed value or panics on invalid input.\n\n# Associated Types\n\n- `Error`: The error type that is returned by the `try_cos` method. This type must implement the [`std::error::Error`] trait.\n\n# Required Methods\n\n - `try_cos`: Computes the cosine of the number and returns a [`Result`]. If the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n - `cos`: Computes the cosine of the number and directly returns the computed value. In Debug mode this method may panic if the computation fails."]                                        ["Computes the *cosine* of `self` and returns a [`Result`].\n\nIf the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n# Errors\n\nThis method returns an error if the computation fails. The error type is defined by the associated [`Error`] type."]          ["Computes and returns the *cosine* of `self`.\n\nIn Debug mode this method may panic if the computation fails.\n\n# Panics\n\nIn Debug mode this method may panic if the computation fails. It is recommended to use the `try_cos` method for safe computations."]           ["The error type that is returned by the `try_cos` method."];
    [Sin]  [try_sin]  [sin]  ["Trait for computing the *sine* of a number.\n\nThis trait defines methods for computing the *sine* of a number. Provides both a fallible method that returns a [`Result`] and a panicking method that directly returns the computed value or panics on invalid input.\n\n# Associated Types\n\n- `Error`: The error type that is returned by the `try_sin` method. This type must implement the [`std::error::Error`] trait.\n\n# Required Methods\n\n - `try_sin`: Computes the sine of the number and returns a [`Result`]. If the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n - `sin`: Computes the sine of the number and directly returns the computed value. In Debug mode this method may panic if the computation fails."]                                                ["Computes the *sine* of `self` and returns a [`Result`].\n\nIf the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n# Errors\n\nThis method returns an error if the computation fails. The error type is defined by the associated [`Error`] type."]            ["Computes and returns the *sine* of `self`.\n\nIn Debug mode this method may panic if the computation fails.\n\n# Panics\n\nIn Debug mode this method may panic if the computation fails. It is recommended to use the `try_sin` method for safe computations."]             ["The error type that is returned by the `try_sin` method."]; 
    [Tan]  [try_tan]  [tan]  ["Trait for computing the *tangent* of a number.\n\nThis trait defines methods for computing the *tangent* of a number. Provides both a fallible method that returns a [`Result`] and a panicking method that directly returns the computed value or panics on invalid input.\n\n# Associated Types\n\n- `Error`: The error type that is returned by the `try_tan` method. This type must implement the [`std::error::Error`] trait.\n\n# Required Methods\n\n - `try_tan`: Computes the tangent of the number and returns a [`Result`]. If the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n - `tan`: Computes the tangent of the number and directly returns the computed value. In Debug mode this method may panic if the computation fails."]                                    ["Computes the *tangent* of `self` and returns a [`Result`].\n\nIf the computation is successful, it returns [`Ok`] with the computed value. If an error occurs, it returns [`Err`] with the associated error.\n\n# Errors\n\nThis method returns an error if the computation fails. The error type is defined by the associated [`Error`] type."]         ["Computes and returns the *tangent* of `self`.\n\nIn Debug mode this method may panic if the computation fails.\n\n# Panics\n\nIn Debug mode this method may panic if the computation fails. It is recommended to use the `try_tan` method for safe computations."]          ["The error type that is returned by the `try_tan` method."];
)]
#[doc = trait_doc]
pub trait T: Sized {
    #[doc = err_doc]
    type Error: std::error::Error;

    #[doc = try_func_doc]
    #[must_use = "this `Result` may contain an error that should be handled"]
    fn try_func(self) -> Result<Self, <Self as T>::Error>;

    #[doc = func_doc]
    fn func(self) -> Self;
}

#[duplicate_item(
    T                trait_name Err                 ErrIn                    try_func   func;
    [f64]            [Sin]      [SinErrors]         [SinInputErrors]         [try_sin]  [sin];
    [f64]            [Cos]      [CosErrors]         [CosInputErrors]         [try_cos]  [cos];
    [f64]            [ATan]     [ATanRealErrors]    [ATanRealInputErrors]    [try_atan] [atan];
    [Complex::<f64>] [Sin]      [SinErrors]         [SinInputErrors]         [try_sin]  [sin];
    [Complex::<f64>] [Cos]      [CosErrors]         [CosInputErrors]         [try_cos]  [cos];
    [Complex::<f64>] [Tan]      [TanComplexErrors]  [TanComplexInputErrors]  [try_tan]  [tan];
    [Complex::<f64>] [ASin]     [ASinComplexErrors] [ASinComplexInputErrors] [try_asin] [asin];
    [Complex::<f64>] [ACos]     [ACosComplexErrors] [ACosComplexInputErrors] [try_acos] [acos];

)]
impl trait_name for T {
    type Error = Err<T>;

    #[inline(always)]
    fn try_func(self) -> Result<Self, Self::Error> {
        StrictFinitePolicy::<T, 53>::validate(self)
            .map_err(|e| ErrIn::InvalidArgument { source: e }.into())
            .and_then(|v| {
                StrictFinitePolicy::<T, 53>::validate(T::func(v))
                    .map_err(|e| Err::Output { source: e })
            })
    }

    #[inline(always)]
    fn func(self) -> Self {
        #[cfg(debug_assertions)]
        {
            self.try_func().unwrap()
        }
        #[cfg(not(debug_assertions))]
        {
            T::func(self)
        }
    }
}

impl Tan for f64 {
    type Error = TanRealErrors<f64>;

    #[inline(always)]
    fn try_tan(self) -> Result<Self, Self::Error> {
        StrictFinitePolicy::<f64, 53>::validate(self)
            .map_err(|e| TanRealInputErrors::InvalidArgument { source: e }.into())
            .and_then(|v| {
                // Check if the cosine of the value is zero, which would indicate a pole
                // for the tangent function (e.g., π/2, 3π/2, etc.).
                // If it is, return an error indicating the argument is a pole.
                // This is a more efficient check than computing the tangent directly.
                // Note: This check is valid because tan(x) = sin(x) / cos(x), and if cos(x) == 0,
                // then tan(x) is undefined (pole).
                if v.cos() == 0. {
                    Err(TanRealInputErrors::ArgumentIsPole {
                        value: v,
                        backtrace: capture_backtrace(),
                    }
                    .into())
                } else {
                    StrictFinitePolicy::<f64, 53>::validate(f64::tan(v))
                        .map_err(|e| TanRealErrors::Output { source: e })
                }
            })
    }

    #[inline(always)]
    fn tan(self) -> Self {
        #[cfg(debug_assertions)]
        {
            self.try_tan().unwrap()
        }
        #[cfg(not(debug_assertions))]
        {
            f64::tan(self)
        }
    }
}

#[duplicate_item(
    T      E                ErrIn                 try_func   func;
    [ASin] [ASinRealErrors] [ASinRealInputErrors] [try_asin] [asin];
    [ACos] [ACosRealErrors] [ACosRealInputErrors] [try_acos] [acos];
)]
impl T for f64 {
    type Error = E<f64>;

    #[inline(always)]
    fn try_func(self) -> Result<Self, <Self as T>::Error> {
        StrictFinitePolicy::<f64, 53>::validate(self)
            .map_err(|e| ErrIn::InvalidArgument { source: e }.into())
            .and_then(|v| {
                if !(-1.0..=1.0).contains(&v) {
                    Err(ErrIn::OutOfDomain {
                        value: v,
                        backtrace: capture_backtrace(),
                    }
                    .into())
                } else {
                    StrictFinitePolicy::<f64, 53>::validate(f64::func(v))
                        .map_err(|e| E::Output { source: e })
                }
            })
    }

    #[inline(always)]
    fn func(self) -> Self {
        #[cfg(debug_assertions)]
        {
            self.try_func().unwrap()
        }
        #[cfg(not(debug_assertions))]
        {
            f64::func(self)
        }
    }
}

impl ATan for Complex<f64> {
    type Error = ATanComplexErrors<Complex<f64>>;

    #[inline(always)]
    fn try_atan(self) -> Result<Self, <Self as ATan>::Error> {
        if self.re == 0. && self.im.abs() == 1. {
            Err(ATanComplexInputErrors::ArgumentIsPole {
                value: self,
                backtrace: capture_backtrace(),
            }
            .into())
        } else {
            StrictFinitePolicy::<Complex<f64>, 53>::validate(self)
                .map_err(|e| ATanComplexInputErrors::InvalidArgument { source: e }.into())
                .and_then(|v| {
                    StrictFinitePolicy::<Complex<f64>, 53>::validate(Complex::<f64>::atan(v))
                        .map_err(|e| Self::Error::Output { source: e })
                })
        }
    }

    #[inline(always)]
    fn atan(self) -> Self {
        #[cfg(debug_assertions)]
        {
            self.try_atan().unwrap()
        }
        #[cfg(not(debug_assertions))]
        {
            Complex::<f64>::atan(self)
        }
    }
}

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

//------------------------------------------------------------------------------------------------
/// Errors that can occur during the input validation phase when attempting to compute
/// the 2-argument arctangent (`atan2`).
///
/// This enum is used as a source for the `Input` variant of [`ATan2Errors`].
/// It is generic over `RawReal: RawRealTrait`, which defines the specific raw real number type
/// (via `RawReal: RawRealTrait`) and its associated validation error type (via `<RawReal as RawScalarTrait>::ValidationErrors`)
/// for the numerator and denominator inputs.
///
/// `atan2(y, x)` computes the principal value of the arctangent of `y/x`, using the
/// signs of both arguments to determine the quadrant of the result.
#[derive(Debug, Error)]
pub enum ATan2InputErrors<RawReal: RawRealTrait> {
    /// The numerator (`y` in `atan2(y, x)`) failed basic validation checks.
    ///
    /// This error occurs if the numerator itself is considered invalid
    /// according to the validation policy (e.g., [`StrictFinitePolicy`]),
    /// such as being NaN or Infinity.
    #[error("the numerator is invalid!")]
    InvalidNumerator {
        /// The underlying validation error from the numerator's raw real type.
        #[source]
        #[backtrace]
        source: <RawReal as RawScalarTrait>::ValidationErrors,
    },

    /// The denominator (`x` in `atan2(y, x)`) failed basic validation checks.
    ///
    /// This error occurs if the denominator itself is considered invalid
    /// according to the validation policy (e.g., [`StrictFinitePolicy`]),
    /// such as being NaN or Infinity.
    #[error("the denominator is invalid!")]
    InvalidDenominator {
        /// The underlying validation error from the denominator's raw real type.
        #[source]
        #[backtrace]
        source: <RawReal as RawScalarTrait>::ValidationErrors,
    },

    /// Both the numerator (`y`) and the denominator (`x`) are zero.
    ///
    /// The `atan2(0, 0)` case is undefined or implementation-specific in many contexts.
    /// This library considers it an error.
    #[error("the numerator and the denominator are both zero!")]
    ZeroOverZero {
        /// A captured backtrace for debugging purposes.
        backtrace: Backtrace,
    },
}

/// A type alias for [`FunctionErrors`], specialized for errors that can occur during
/// the computation of the 2-argument arctangent (`atan2`).
///
/// This type represents the possible failures when calling [`ATan2::try_atan2()`].
///
/// # Generic Parameters
///
/// - `RawReal`: A type that implements [`RawRealTrait`]. This type parameter defines:
///   - The type for the input arguments of `atan2` via [`ATan2InputErrors<RawReal>`].
///   - The raw error type for validating the real number inputs and the output, via `<RawReal as RawScalarTrait>::RawErrors`.
///     This is typically [`crate::core::errors::ErrorsValidationRawReal<f64>`] for `f64` or a similar type
///     for other numeric backends.
///
/// # Variants
///
/// This type alias wraps [`FunctionErrors`], which has the following variants in this context:
///
/// - `Input { source: ATan2InputErrors<RawReal> }`:
///   Indicates that one or both input arguments (`y` or `x` in `atan2(y, x)`) were invalid.
///   This could be due to:
///     - The numerator failing general validation checks (e.g., NaN, Infinity).
///     - The denominator failing general validation checks (e.g., NaN, Infinity).
///     - Both numerator and denominator being zero.
///
///   The `source` field provides more specific details via [`ATan2InputErrors`].
///
/// - `Output { source: <RawReal as RawScalarTrait>::RawErrors }`:
///   Indicates that the computed result of `atan2` itself failed validation.
///   This typically means the result yielded a non-finite value (e.g., NaN or Infinity),
///   which should generally not happen if the inputs are valid and finite (excluding 0/0).
///   The `source` field contains the raw validation error for the output real number.
pub type ATan2Errors<RawReal> =
    FunctionErrors<ATan2InputErrors<RawReal>, <RawReal as RawScalarTrait>::ValidationErrors>;

/// Trait for computing the [*2-argument arctangent*](https://en.wikipedia.org/wiki/Atan2)
/// of two numbers, `y` (self) and `x` (denominator).
///
/// The `atan2(y, x)` function calculates the principal value of the arctangent of `y/x`,
/// using the signs of both arguments to determine the correct quadrant of the result.
/// The result is an angle in radians, typically in the range `(-π, π]`.
///
/// This trait provides two methods:
/// - [`try_atan2`](ATan2::try_atan2): A fallible version that performs validation on
///   both inputs (numerator `self` and denominator `x`) and potentially the output.
///   It returns a [`Result`]. This is the preferred method for robust error handling.
/// - [`atan2`](ATan2::atan2): A convenient infallible version that panics if `try_atan2`
///   would return an error in debug builds, or directly computes the value in release builds.
///   Use this when inputs are known to be valid or when panicking on error is acceptable.
///
/// # Associated Types
///
/// - `Error`: The error type returned by the [`try_atan2`](ATan2::try_atan2) method.
///   This type must implement [`std::error::Error`]. For `f64`, this is typically
///   [`ATan2Errors<f64>`].
///
/// # Required Methods
///
/// - `try_atan2(self, denominator: &Self) -> Result<Self, Self::Error>`:
///   Attempts to compute `atan2(self, denominator)`.
///   Validates both `self` (numerator) and `denominator` using [`StrictFinitePolicy`].
///   Also considers the case `atan2(0, 0)` as an error ([`ATan2InputErrors::ZeroOverZero`]).
///   The output is also validated using [`StrictFinitePolicy`].
///
/// - `atan2(self, denominator: &Self) -> Self`:
///   Computes `atan2(self, denominator)` directly.
///   In debug builds, this calls `try_atan2` and unwraps.
///   In release builds, this typically calls the underlying standard library's `atan2` function.
///
/// # Example
///
/// ```
/// use num_valid::{functions::ATan2, backends::native64::raw::Native64}; // Assuming Native64 implements ATan2
///
/// let y = 1.0; // Represents the numerator
/// let x = 1.0; // Represents the denominator
///
/// // Using the fallible method
/// match y.try_atan2(&x) {
///     Ok(result) => println!("atan2(y, x): {}", result), // Expected: π/4 (approx 0.785)
///     Err(e) => println!("Error: {:?}", e),
/// }
///
/// // Using the infallible method (panics on error in debug)
/// let result = y.atan2(x);
/// println!("atan2(y, x): {}", result);
///
/// // Example of an error case (0/0)
/// let y_zero = 0.0;
/// let x_zero = 0.0;
/// match y_zero.try_atan2(&x_zero) {
///     Ok(_) => println!("This should not happen for 0/0"),
///     Err(e) => println!("Error for atan2(0,0): {:?}", e), // Expected: ZeroOverZero error
/// }
/// ```
pub trait ATan2: Sized {
    /// The error type that is returned by the `try_atan2` method.
    type Error: std::error::Error;

    /// Computes the arctangent of `self` (numerator `y`) and `denominator` (`x`),
    /// returning a [`Result`].
    ///
    /// This method validates both inputs to ensure they are finite numbers
    /// (not NaN, Infinity, or subnormal) using the [`StrictFinitePolicy`].
    /// The specific case where both `self` and `denominator` are zero is
    /// considered an error ([`ATan2InputErrors::ZeroOverZero`]).
    /// The computed result is also validated to be a finite number.
    ///
    /// # Arguments
    ///
    /// * `self`: The numerator `y` of the `atan2(y, x)` operation.
    /// * `denominator`: A reference to the denominator `x` of the `atan2(y, x)` operation.
    ///
    /// # Errors
    ///
    /// Returns `Err(Self::Error)` if:
    /// - Either `self` or `denominator` fails validation (e.g., NaN, Infinity).
    /// - Both `self` and `denominator` are zero.
    /// - The computed result fails validation (e.g., results in NaN or Infinity,
    ///   though this is less common for `atan2` with valid finite inputs).
    #[must_use = "this `Result` may contain an error that should be handled"]
    fn try_atan2(self, denominator: &Self) -> Result<Self, Self::Error>;

    /// Computes the arctangent of `self` (numerator `y`) and `denominator` (`x`),
    /// returning the result directly.
    fn atan2(self, denominator: &Self) -> Self;
}

impl ATan2 for f64 {
    /// The error type that is returned by the `try_atan2` method.
    type Error = ATan2Errors<f64>;

    /// Computes the arctangent of `self` (numerator `y`) and `denominator` (`x`),
    /// returning a [`Result`].
    ///
    /// This method validates both inputs to ensure they are finite numbers
    /// (not NaN, Infinity, or subnormal) using the [`StrictFinitePolicy`].
    /// The specific case where both `self` and `denominator` are zero is
    /// considered an error ([`ATan2InputErrors::ZeroOverZero`]).
    /// The computed result is also validated to be a finite number.
    ///
    /// # Arguments
    ///
    /// * `self`: The numerator `y` of the `atan2(y, x)` operation.
    /// * `denominator`: A reference to the denominator `x` of the `atan2(y, x)` operation.
    ///
    /// # Errors
    ///
    /// Returns `Err(Self::Error)` if:
    /// - Either `self` or `denominator` fails validation (e.g., NaN, Infinity).
    /// - Both `self` and `denominator` are zero.
    /// - The computed result fails validation (e.g., results in NaN or Infinity,
    ///   though this is less common for `atan2` with valid finite inputs).
    ///
    /// # Note on Infinite Inputs
    ///
    /// This implementation, using `StrictFinitePolicy`, rejects infinite inputs and
    /// returns an `InvalidArgument` error. This differs from some standard library
    /// implementations (like `libm` or `std::f64::atan2`) which may return specific
    /// values for infinite arguments.
    fn try_atan2(self, denominator: &Self) -> Result<Self, Self::Error> {
        // Validate the denominator
        let denominator = StrictFinitePolicy::<f64, 53>::validate(*denominator)
            .map_err(|e| ATan2InputErrors::InvalidDenominator { source: e })?;

        // Validate the numerator
        let numerator = StrictFinitePolicy::<f64, 53>::validate(self)
            .map_err(|e| ATan2InputErrors::InvalidNumerator { source: e })?;

        // Check for the specific case of 0/0
        // This is a special case that is often considered undefined or implementation-specific.
        // Here, we treat it as an error.
        // Note: This is different from the standard library's behavior, which returns NaN.
        if numerator == 0.0 && denominator == 0.0 {
            Err(ATan2InputErrors::ZeroOverZero {
                backtrace: capture_backtrace(),
            }
            .into())
        } else {
            StrictFinitePolicy::<f64, 53>::validate(f64::atan2(self, denominator))
                .map_err(|e| ATan2Errors::Output { source: e })
        }
    }

    /// Computes the arctangent of `self` (numerator `y`) and `denominator` (`x`),
    /// returning the result directly.
    ///
    /// # Behavior
    ///
    /// - In **debug builds** (`#[cfg(debug_assertions)]`): This method calls
    ///   [`try_atan2()`](ATan2::try_atan2) and unwraps the result. It will panic if `try_atan2`
    ///   returns an error.
    /// - In **release builds** (`#[cfg(not(debug_assertions))]`): This method typically
    ///   calls the underlying standard library's `atan2` function directly for performance,
    ///   bypassing the explicit validations performed by `try_atan2`.
    ///
    /// # Arguments
    ///
    /// * `self`: The numerator `y` of the `atan2(y, x)` operation.
    /// * `denominator`: A reference to the denominator `x` of the `atan2(y, x)` operation.
    ///
    /// # Panics
    ///
    /// This method will panic in debug builds if `try_atan2()` would return an `Err`.
    /// In release builds, the behavior for invalid inputs (like NaN or Infinity)
    /// will match the underlying standard library function (e.g., `f64::atan2(f64::NAN, 1.0)` is `NAN`).
    fn atan2(self, denominator: &Self) -> Self {
        #[cfg(debug_assertions)]
        {
            self.try_atan2(denominator).unwrap()
        }
        #[cfg(not(debug_assertions))]
        {
            f64::atan2(self, *denominator)
        }
    }
}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
/// A convenience trait that aggregates the standard trigonometric functions and their inverses.
///
/// This trait serves as a shorthand for requiring a type to implement all the fundamental
/// trigonometric operations:
/// - [`Sin`] and [`ASin`]
/// - [`Cos`] and [`ACos`]
/// - [`Tan`] and [`ATan`]
///
/// It is primarily used as a super-trait for [`FpScalar`](crate::FpScalar) to simplify trait bounds
/// and ensure that any scalar type in the library provides a comprehensive set of trigonometric
/// capabilities. By using `TrigonometricFunctions` as a bound, you can write generic functions that
/// utilize any of its constituent trait methods.
///
/// # Examples
///
/// ```
/// use num_valid::{FpScalar ,functions::{TrigonometricFunctions, Sin, Cos}};
/// use std::ops::{Add, Mul};
///
/// // A generic function that verifies the identity sin(x)^2 + cos(x)^2 = 1.
/// // We bound T by FpScalar which implies TrigonometricFunctions, Clone, and arithmetic ops.
/// fn verify_trig_identity<T>(x: T) -> T
/// where
///     T: TrigonometricFunctions + Clone + Mul<Output = T> + Add<Output = T>,
/// {
///     let sin_x = x.clone().sin();
///     let cos_x = x.cos();
///     // This works because FpScalar requires the necessary arithmetic traits.
///     sin_x.clone() * sin_x + cos_x.clone() * cos_x
/// }
///
/// let angle = 0.5f64;
/// let identity = verify_trig_identity(angle);
///
/// // The result should be very close to 1.0.
/// assert!((identity - 1.0).abs() < 1e-15);
/// ```
pub trait TrigonometricFunctions: Sin + ASin + Cos + ACos + Tan + ATan {}

#[duplicate_item(
    T;
    [f64];
    [Complex<f64>];
)]
impl TrigonometricFunctions for T {}
//------------------------------------------------------------------------------------------------

//------------------------------------------------------------------------------------------------
#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_ulps_eq;
    use num::Complex;

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

    #[cfg(feature = "rug")]
    use try_create::TryNew;

    mod sin {
        use super::*;

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn sin_valid() {
                    let value = 4.0;
                    let expected_result = -0.7568024953079282;
                    assert_ulps_eq!(value.try_sin().unwrap(), expected_result);
                    assert_ulps_eq!(value.sin(), expected_result);
                }

                #[test]
                fn sin_negative() {
                    let value = -4.0;
                    let expected_result = 0.7568024953079282;
                    assert_ulps_eq!(value.try_sin().unwrap(), expected_result);
                    assert_ulps_eq!(value.sin(), expected_result);
                }

                #[test]
                fn sin_zero() {
                    let value = 0.0;
                    assert_eq!(value.try_sin().unwrap(), 0.0);
                    assert_eq!(value.sin(), 0.0);
                }

                #[test]
                fn sin_nan() {
                    let value = f64::NAN;
                    let result = value.try_sin();
                    assert!(matches!(result, Err(SinErrors::Input { .. })));
                }

                #[test]
                fn sin_infinity() {
                    let value = f64::INFINITY;
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));
                }

                #[test]
                fn sin_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn sin_valid() {
                    let value = Complex::new(4.0, 1.0);
                    let expected_result = if cfg!(target_arch = "x86_64") {
                        Complex::new(-1.1678072748895183, -0.7681627634565731)
                    } else if cfg!(target_arch = "aarch64") {
                        Complex::new(-1.1678072748895185, -0.7681627634565731)
                    } else {
                        todo!("Architecture not-tested");
                    };

                    assert_eq!(value.try_sin().unwrap(), expected_result);
                    assert_eq!(<Complex<f64> as Sin>::sin(value), expected_result);
                    assert_eq!(value.sin(), expected_result);
                }

                #[test]
                fn sin_zero() {
                    let value = Complex::new(0.0, 0.0);
                    let expected_result = Complex::new(0.0, 0.0);
                    assert_eq!(value.try_sin().unwrap(), expected_result);
                    assert_eq!(value.sin(), expected_result);
                }

                #[test]
                fn sin_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));
                }

                #[test]
                fn sin_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));
                }

                #[test]
                fn sin_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(value.try_sin(), Err(SinErrors::Input { .. })));
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn test_rug_float_sin_valid() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, -4.0)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        7.568024953079282e-1,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_sin().unwrap(), expected_result);
                    assert_eq!(value.sin(), expected_result);
                }

                #[test]
                fn test_rug_float_sin_zero() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();

                    let expected_result =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();
                    assert_eq!(value.clone().try_sin().unwrap(), expected_result);
                    assert_eq!(value.sin(), expected_result);
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn test_complex_rug_float_sin_valid() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 4.0), rug::Float::with_val(53, 1.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, -1.1678072748895185),
                                rug::Float::with_val(53, -7.681627634565731e-1),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_sin().unwrap(), expected_result);
                    assert_eq!(value.sin(), expected_result);
                }

                #[test]
                fn test_complex_rug_float_sin_zero() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.0), rug::Float::with_val(53, 0.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (rug::Float::with_val(53, 0.), rug::Float::with_val(53, 0.)),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_sin().unwrap(), expected_result);
                    assert_eq!(value.sin(), expected_result);
                }
            }
        }
    }

    mod cos {
        use super::*;

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn cos_valid() {
                    let value = 4.0;
                    let expected_result = -0.6536436208636119;
                    assert_eq!(value.try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }

                #[test]
                fn cos_negative() {
                    let value = -4.0;
                    let expected_result = -0.6536436208636119;
                    assert_eq!(value.try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }

                #[test]
                fn cos_zero() {
                    let value = 0.0;
                    assert_eq!(value.try_cos().unwrap(), 1.0);
                    assert_eq!(value.cos(), 1.0);
                }

                #[test]
                fn cos_nan() {
                    let value = f64::NAN;
                    let result = value.try_cos();
                    assert!(matches!(result, Err(CosErrors::Input { .. })));
                }

                #[test]
                fn cos_infinity() {
                    let value = f64::INFINITY;
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));
                }

                #[test]
                fn cos_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn cos_valid() {
                    let value = Complex::new(4.0, 1.0);
                    let expected_result = if cfg!(target_arch = "x86_64") {
                        Complex::new(-1.0086248134251568, 0.8893951958384846)
                    } else if cfg!(target_arch = "aarch64") {
                        Complex::new(-1.0086248134251568, 0.8893951958384847)
                    } else {
                        todo!("Architecture not-tested");
                    };
                    assert_eq!(value.try_cos().unwrap(), expected_result);
                    assert_eq!(<Complex<f64> as Cos>::cos(value), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }

                #[test]
                fn cos_zero() {
                    let value = Complex::new(0.0, 0.0);
                    let expected_result = Complex::new(1.0, 0.0);
                    assert_eq!(value.try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }

                #[test]
                fn cos_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));
                }

                #[test]
                fn cos_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));
                }

                #[test]
                fn cos_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(value.try_cos(), Err(CosErrors::Input { .. })));
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn test_rug_float_cos_valid() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, -4.0)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        -0.6536436208636119,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }

                #[test]
                fn test_rug_float_cos_zero() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();

                    let expected_result =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 1.0)).unwrap();
                    assert_eq!(value.clone().try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn test_complex_rug_float_cos_valid() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 4.0), rug::Float::with_val(53, 1.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, -1.0086248134251568),
                                rug::Float::with_val(53, 8.893951958384847e-1),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }

                #[test]
                fn test_complex_rug_float_cos_zero() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.0), rug::Float::with_val(53, 0.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (rug::Float::with_val(53, 1.), rug::Float::with_val(53, 0.)),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_cos().unwrap(), expected_result);
                    assert_eq!(value.cos(), expected_result);
                }
            }
        }
    }

    mod tan {
        use super::*;

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn tan_valid() {
                    let value = 4.0;
                    let expected_result = 1.1578212823495775;
                    assert_eq!(value.try_tan().unwrap(), expected_result);
                    assert_eq!(<f64 as Tan>::tan(value), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                /*
                #[test]
                #[ignore = "at the moment we cannot generate a pole for the Tan function"]
                fn tan_argument_pole() {
                    let value = f64::pi_div_2();
                    let err = value.try_tan().unwrap_err();
                    assert!(matches!(
                        err,
                        TanRealErrors::Input {
                            source: TanRealInputErrors::ArgumentIsPole { .. }
                        }
                    ));
                }
                */

                #[test]
                fn tan_negative() {
                    let value = -4.0;
                    let expected_result = -1.1578212823495775;
                    assert_eq!(value.try_tan().unwrap(), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                #[test]
                fn tan_zero() {
                    let value = 0.0;
                    assert_eq!(value.try_tan().unwrap(), 0.0);
                    assert_eq!(value.tan(), 0.0);
                }

                #[test]
                fn tan_nan() {
                    let value = f64::NAN;
                    let result = value.try_tan();
                    assert!(matches!(result, Err(TanRealErrors::Input { .. })));
                }

                #[test]
                fn tan_infinity() {
                    let value = f64::INFINITY;
                    assert!(matches!(value.try_tan(), Err(TanRealErrors::Input { .. })));
                }

                #[test]
                fn tan_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert!(matches!(value.try_tan(), Err(TanRealErrors::Input { .. })));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn tan_valid() {
                    let value = Complex::new(4.0, 1.0);
                    let expected_result = Complex::new(0.27355308280730734, 1.002810507583505);
                    assert_eq!(value.try_tan().unwrap(), expected_result);
                    assert_eq!(<Complex<f64> as Tan>::tan(value), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                #[test]
                fn tan_zero() {
                    let value = Complex::new(0.0, 0.0);
                    let expected_result = Complex::new(0.0, 0.0);
                    assert_eq!(value.try_tan().unwrap(), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                #[test]
                fn tan_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn tan_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn tan_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn test_rug_float_tan_valid() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, -4.0)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        -1.1578212823495775,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_tan().unwrap(), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                #[cfg(feature = "rug")]
                #[test]
                fn test_rug_float_tan_zero() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();

                    let expected_result =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();
                    assert_eq!(value.clone().try_tan().unwrap(), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                /*
                #[cfg(feature = "rug")]
                #[test]
                fn test_rug_float_tan_nan() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, rug::float::Special::Nan))
                            .unwrap();
                    let result = value.try_tan();
                    assert!(matches!(result, Err(TanRealErrors::Input { .. })));
                }


                #[cfg(feature = "rug")]
                #[test]
                fn test_rug_float_tan_infinite() {
                    let value = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        rug::float::Special::Infinity,
                    ))
                    .unwrap();
                    let result = value.try_tan();
                    assert!(matches!(result, Err(TanRealErrors::Input { .. })));
                }
                */
            }

            mod complex {
                use super::*;

                #[test]
                fn test_complex_rug_float_tan_valid() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 4.0), rug::Float::with_val(53, 1.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, 2.7355308280730734e-1),
                                rug::Float::with_val(53, 1.002810507583505),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_tan().unwrap(), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                #[test]
                fn test_complex_rug_float_tan_zero() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.0), rug::Float::with_val(53, 0.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (rug::Float::with_val(53, 0.), rug::Float::with_val(53, 0.)),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_tan().unwrap(), expected_result);
                    assert_eq!(value.tan(), expected_result);
                }

                /*

                #[test]
                fn test_complex_rug_float_tan_nan() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (
                            rug::Float::with_val(53, rug::float::Special::Nan),
                            rug::Float::with_val(53, 0.0),
                        ),
                    ))
                    .unwrap();
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn test_complex_rug_float_tan_infinite() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (
                            rug::Float::with_val(53, rug::float::Special::Infinity),
                            rug::Float::with_val(53, 0.0),
                        ),
                    ))
                    .unwrap();
                    assert!(matches!(
                        value.try_tan(),
                        Err(TanComplexErrors::Input { .. })
                    ));
                }
                */
            }
        }
    }

    mod atan {
        use super::*;

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn atan_valid() {
                    let value = 4.0;
                    let expected_result = 1.3258176636680326;
                    assert_eq!(value.try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }

                #[test]
                fn atan_negative() {
                    let value = -4.0;
                    let expected_result = -1.3258176636680326;
                    assert_eq!(value.try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }

                #[test]
                fn atan_zero() {
                    let value = 0.0;
                    assert_eq!(value.try_atan().unwrap(), 0.0);
                    assert_eq!(value.atan(), 0.0);
                }

                #[test]
                fn atan_nan() {
                    let value = f64::NAN;
                    let result = value.try_atan();
                    assert!(matches!(result, Err(ATanRealErrors::Input { .. })));
                }

                #[test]
                fn atan_infinity() {
                    let value = f64::INFINITY;
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanRealErrors::Input { .. })
                    ));
                }

                #[test]
                fn atan_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanRealErrors::Input { .. })
                    ));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn atan_valid() {
                    let value = Complex::new(4.0, 1.0);
                    let expected_result = Complex::new(1.3389725222944935, 0.05578588782855254);
                    assert_eq!(value.try_atan().unwrap(), expected_result);
                    assert_eq!(<Complex<f64> as ATan>::atan(value), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }

                #[test]
                fn atan_out_of_domain() {
                    let value = Complex::new(0.0, 1.0);
                    let err = value.try_atan().unwrap_err();
                    assert!(matches!(
                        err,
                        ATanComplexErrors::Input {
                            source: ATanComplexInputErrors::ArgumentIsPole { .. }
                        }
                    ));

                    let value = Complex::new(0.0, -1.0);
                    let err = value.try_atan().unwrap_err();
                    assert!(matches!(
                        err,
                        ATanComplexErrors::Input {
                            source: ATanComplexInputErrors::ArgumentIsPole { .. }
                        }
                    ));
                }

                #[test]
                fn atan_zero() {
                    let value = Complex::new(0.0, 0.0);
                    let expected_result = Complex::new(0.0, 0.0);
                    assert_eq!(value.try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }

                #[test]
                fn atan_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn atan_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn atan_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(
                        value.try_atan(),
                        Err(ATanComplexErrors::Input { .. })
                    ));
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn test_rug_float_atan_valid() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, -4.0)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        -1.3258176636680326,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }

                #[test]
                fn test_rug_float_atan_zero() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();

                    let expected_result =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();
                    assert_eq!(value.clone().try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn test_complex_rug_float_atan_valid() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 4.0), rug::Float::with_val(53, 1.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, 1.3389725222944935),
                                rug::Float::with_val(53, 5.578588782855244e-2),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }

                #[test]
                fn test_complex_rug_float_atan_zero() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.0), rug::Float::with_val(53, 0.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (rug::Float::with_val(53, 0.), rug::Float::with_val(53, 0.)),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_atan().unwrap(), expected_result);
                    assert_eq!(value.atan(), expected_result);
                }
            }
        }
    }

    mod asin {
        use super::*;

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn asin_valid() {
                    let value = 0.5;
                    let expected_result = std::f64::consts::FRAC_PI_6;

                    assert_ulps_eq!(value.try_asin().unwrap(), expected_result);
                    assert_ulps_eq!(value.asin(), expected_result);
                }

                #[test]
                fn asin_negative() {
                    let value = -0.5;
                    let expected_result = -std::f64::consts::FRAC_PI_6;

                    assert_ulps_eq!(value.try_asin().unwrap(), expected_result);
                    assert_ulps_eq!(value.asin(), expected_result);
                }

                #[test]
                fn asin_zero() {
                    let value = 0.0;
                    assert_eq!(value.try_asin().unwrap(), 0.0);
                    assert_eq!(value.asin(), 0.0);
                }

                #[test]
                fn test_rug_float_asin_out_of_bound() {
                    let value = 2.0;
                    let result = value.try_asin();
                    println!("result: {result:?}");
                    assert!(matches!(result, Err(ASinRealErrors::Input { .. })));
                }

                #[test]
                fn asin_nan() {
                    let value = f64::NAN;
                    let result = value.try_asin();
                    assert!(matches!(result, Err(ASinRealErrors::Input { .. })));
                }

                #[test]
                fn asin_infinity() {
                    let value = f64::INFINITY;
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinRealErrors::Input { .. })
                    ));
                }

                #[test]
                fn asin_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinRealErrors::Input { .. })
                    ));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn asin_valid() {
                    let value = Complex::new(0.5, 0.5);
                    let expected_result = Complex::new(0.4522784471511907, 0.5306375309525178);
                    assert_eq!(value.try_asin().unwrap(), expected_result);
                    assert_eq!(<Complex<f64> as ASin>::asin(value), expected_result);
                    assert_eq!(value.asin(), expected_result);
                }

                #[test]
                fn asin_zero() {
                    let value = Complex::new(0.0, 0.0);
                    let expected_result = Complex::new(0.0, 0.0);
                    assert_eq!(value.try_asin().unwrap(), expected_result);
                    assert_eq!(value.asin(), expected_result);
                }

                #[test]
                fn asin_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn asin_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn asin_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(
                        value.try_asin(),
                        Err(ASinComplexErrors::Input { .. })
                    ));
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn test_rug_float_asin_valid() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.5)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        std::f64::consts::FRAC_PI_6,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_asin().unwrap(), expected_result);
                    assert_eq!(value.asin(), expected_result);
                }

                #[test]
                fn test_rug_float_asin_zero() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();

                    let expected_result =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();
                    assert_eq!(value.clone().try_asin().unwrap(), expected_result);
                    assert_eq!(value.asin(), expected_result);
                }

                #[test]
                fn test_rug_float_asin_out_of_bound() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 2.0)).unwrap();
                    let result = value.try_asin();
                    println!("result: {result:?}");
                    assert!(matches!(result, Err(ASinRealErrors::Input { .. })));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn test_complex_rug_float_asin_valid() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.5), rug::Float::with_val(53, 0.5)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, 0.4522784471511907),
                                rug::Float::with_val(53, 0.5306375309525179),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_asin().unwrap(), expected_result);
                    assert_eq!(value.asin(), expected_result);
                }

                #[test]
                fn test_complex_rug_float_asin_zero() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.0), rug::Float::with_val(53, 0.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (rug::Float::with_val(53, 0.), rug::Float::with_val(53, 0.)),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_asin().unwrap(), expected_result);
                    assert_eq!(value.asin(), expected_result);
                }
            }
        }
    }

    mod acos {
        use super::*;

        mod native64 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn acos_valid() {
                    let value = 0.5;
                    let expected_result = std::f64::consts::FRAC_PI_3;

                    assert_ulps_eq!(value.try_acos().unwrap(), expected_result);
                    assert_ulps_eq!(value.acos(), expected_result);
                }

                #[test]
                fn acos_negative() {
                    let value = -0.5;
                    let expected_result = 2.0943951023931957;
                    assert_eq!(value.try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn acos_zero() {
                    let value = 0.0;
                    let expected_result = std::f64::consts::FRAC_PI_2;
                    assert_eq!(value.try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn test_rug_float_acos_out_of_bound() {
                    let value = 2.0;
                    let result = value.try_acos();
                    println!("result: {result:?}");
                    assert!(matches!(result, Err(ACosRealErrors::Input { .. })));
                }

                #[test]
                fn acos_nan() {
                    let value = f64::NAN;
                    let result = value.try_acos();
                    assert!(matches!(result, Err(ACosRealErrors::Input { .. })));
                }

                #[test]
                fn acos_infinity() {
                    let value = f64::INFINITY;
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosRealErrors::Input { .. })
                    ));
                }

                #[test]
                fn acos_subnormal() {
                    let value = f64::MIN_POSITIVE / 2.0;
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosRealErrors::Input { .. })
                    ));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn acos_valid() {
                    let value = Complex::new(0.5, 0.5);
                    let expected_result = Complex::new(1.118517879643706, -0.5306375309525179);
                    assert_eq!(value.try_acos().unwrap(), expected_result);
                    assert_eq!(<Complex<f64> as ACos>::acos(value), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn acos_zero() {
                    let value = Complex::new(0.0, 0.0);
                    let expected_result = Complex::new(std::f64::consts::FRAC_PI_2, 0.0);
                    assert_eq!(value.try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn acos_nan() {
                    let value = Complex::new(f64::NAN, 0.0);
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::NAN);
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn acos_infinity() {
                    let value = Complex::new(f64::INFINITY, 0.0);
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::INFINITY);
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosComplexErrors::Input { .. })
                    ));
                }

                #[test]
                fn acos_subnormal() {
                    let value = Complex::new(f64::MIN_POSITIVE / 2.0, 0.0);
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosComplexErrors::Input { .. })
                    ));

                    let value = Complex::new(0.0, f64::MIN_POSITIVE / 2.0);
                    assert!(matches!(
                        value.try_acos(),
                        Err(ACosComplexErrors::Input { .. })
                    ));
                }
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;

            mod real {
                use super::*;

                #[test]
                fn test_rug_float_acos_valid() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.5)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        std::f64::consts::FRAC_PI_3,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn test_rug_float_acos_zero() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 0.0)).unwrap();

                    let expected_result = RealRugStrictFinite::<53>::try_new(rug::Float::with_val(
                        53,
                        std::f64::consts::FRAC_PI_2,
                    ))
                    .unwrap();
                    assert_eq!(value.clone().try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn test_rug_float_acos_out_of_bound() {
                    let value =
                        RealRugStrictFinite::<53>::try_new(rug::Float::with_val(53, 2.0)).unwrap();
                    let result = value.try_acos();
                    println!("result: {result:?}");
                    assert!(matches!(result, Err(ACosRealErrors::Input { .. })));
                }
            }

            mod complex {
                use super::*;

                #[test]
                fn test_complex_rug_float_acos_valid() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.5), rug::Float::with_val(53, 0.5)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, 1.1185178796437059),
                                rug::Float::with_val(53, -5.306375309525179e-1),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }

                #[test]
                fn test_complex_rug_float_acos_zero() {
                    let value = ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                        53,
                        (rug::Float::with_val(53, 0.0), rug::Float::with_val(53, 0.0)),
                    ))
                    .unwrap();

                    let expected_result =
                        ComplexRugStrictFinite::<53>::try_new(rug::Complex::with_val(
                            53,
                            (
                                rug::Float::with_val(53, std::f64::consts::FRAC_PI_2),
                                rug::Float::with_val(53, 0.),
                            ),
                        ))
                        .unwrap();
                    assert_eq!(value.clone().try_acos().unwrap(), expected_result);
                    assert_eq!(value.acos(), expected_result);
                }
            }
        }
    }

    mod atan2 {
        use super::*;

        mod native64 {
            use super::*;

            #[test]
            fn atan2_valid() {
                let numerator = 1.0;
                let denominator = 1.0;
                let expected_result = std::f64::consts::FRAC_PI_4; // 45 degrees in radians
                assert_eq!(numerator.atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn atan2_zero_numerator() {
                let numerator = 0.0;
                let denominator = 1.0;
                let expected_result = 0.0;
                assert_eq!(numerator.atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn atan2_zero_denominator() {
                let numerator = 1.0;
                let denominator = 0.0;
                let expected_result = std::f64::consts::FRAC_PI_2; // 90 degrees in radians
                assert_eq!(numerator.atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn atan2_zero_over_zero() {
                let numerator = 0.0;
                let denominator = 0.0;
                let result = numerator.try_atan2(&denominator);
                assert!(matches!(
                    result,
                    Err(ATan2Errors::Input {
                        source: ATan2InputErrors::ZeroOverZero { .. }
                    })
                ));
            }

            #[test]
            fn atan2_negative_numerator() {
                let numerator = -1.0;
                let denominator = 1.0;
                let expected_result = -std::f64::consts::FRAC_PI_4; // -45 degrees in radians
                assert_eq!(numerator.atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn atan2_negative_denominator() {
                let numerator = 1.0;
                let denominator = -1.0;
                let expected_result = 2.356194490192345; // 135 degrees in radians
                assert_eq!(numerator.atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn atan2_nan_numerator() {
                let numerator = f64::NAN;
                let denominator = 1.0;
                let result = numerator.try_atan2(&denominator);
                assert!(result.is_err());
            }

            #[test]
            fn atan2_nan_denominator() {
                let numerator = 1.0;
                let denominator = f64::NAN;
                let result = numerator.try_atan2(&denominator);
                assert!(result.is_err());
            }
        }

        #[cfg(feature = "rug")]
        mod rug53 {
            use super::*;
            use rug::Float;

            #[test]
            fn test_realrug_atan2_valid() {
                let numerator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 1.0)).unwrap();
                let denominator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 1.0)).unwrap();
                let expected_result = RealRugStrictFinite::<53>::try_new(Float::with_val(
                    53,
                    std::f64::consts::FRAC_PI_4,
                ))
                .unwrap(); // 45 degrees in radians
                assert_eq!(numerator.clone().atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn test_realrug_atan2_zero_numerator() {
                let numerator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 0.0)).unwrap();
                let denominator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 1.0)).unwrap();
                let expected_result =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 0.0)).unwrap();
                assert_eq!(numerator.clone().atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn test_realrug_atan2_zero_denominator() {
                let numerator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 1.0)).unwrap();
                let denominator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 0.0)).unwrap();
                let expected_result = RealRugStrictFinite::<53>::try_new(Float::with_val(
                    53,
                    std::f64::consts::FRAC_PI_2,
                ))
                .unwrap(); // 90 degrees in radians
                assert_eq!(numerator.clone().atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn test_realrug_atan2_zero_over_zero() {
                let numerator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 0.0)).unwrap();
                let denominator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 0.0)).unwrap();
                let result = numerator.try_atan2(&denominator);
                assert!(matches!(
                    result,
                    Err(ATan2Errors::Input {
                        source: ATan2InputErrors::ZeroOverZero { .. }
                    })
                ));
            }

            #[test]
            fn test_realrug_atan2_negative_numerator() {
                let numerator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, -1.0)).unwrap();
                let denominator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 1.0)).unwrap();
                let expected_result = RealRugStrictFinite::<53>::try_new(Float::with_val(
                    53,
                    -std::f64::consts::FRAC_PI_4,
                ))
                .unwrap(); // -45 degrees in radians
                assert_eq!(numerator.clone().atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }

            #[test]
            fn test_realrug_atan2_negative_denominator() {
                let numerator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 1.0)).unwrap();
                let denominator =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, -1.0)).unwrap();
                let expected_result =
                    RealRugStrictFinite::<53>::try_new(Float::with_val(53, 2.356194490192345))
                        .unwrap(); // 135 degrees in radians
                assert_eq!(numerator.clone().atan2(&denominator), expected_result);
                assert_eq!(numerator.try_atan2(&denominator).unwrap(), expected_result);
            }
        }
    }
}
//------------------------------------------------------------------------------------------------