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

//! # Native 64-bit Floating-Point Kernel
//!
//! This module provides a numerical kernel implementation based on Rust's native
//! 64-bit floating-point numbers ([`f64`]) and complex numbers ([`num::Complex<f64>`](num::Complex)).
//! It serves as the standard, high-performance double-precision backend for the
//! [`num-valid`](crate) library.
//!
//! ## Purpose and Role
//!
//! The primary role of this module is to act as a **bridge** between the abstract traits
//! defined by [`num-valid`](crate) (like [`RealScalar`](crate::RealScalar) and [`ComplexScalar`](crate::ComplexScalar)) and Rust's
//! concrete, hardware-accelerated numeric types. It adapts [`f64`] and [`Complex<f64>`](num::Complex)
//! so they can be used seamlessly in generic code written against the library's traits.
//!
//! ### `f64` as a `RealScalar`
//!
//! By implementing [`RealScalar`](crate::RealScalar) for [`f64`], this module makes Rust's native float
//! a "first-class citizen" in the [`num-valid`](crate) ecosystem. This implementation
//! provides concrete logic for all the operations required by [`RealScalar`](crate::RealScalar) and its
//! super-traits (e.g., [`FpScalar`](crate::FpScalar), [`Rounding`](crate::functions::Rounding), [`Sign`](crate::functions::Sign), [`Constants`](crate::Constants)).
//! Most of these implementations simply delegate to the highly optimized methods
//! available in Rust's standard library (e.g., `f64::sin`, `f64::sqrt`).
//!
//! This allows generic functions bounded by `T: RealScalar` to be instantiated with `f64`,
//! leveraging direct CPU floating-point support for maximum performance.
//!
//! ### `Complex<f64>` as a `ComplexScalar`
//!
//! Similarly, this module implements [`ComplexScalar`](crate::ComplexScalar) for [`num::Complex<f64>`](num::Complex). This
//! makes the standard complex number type from the `num` crate compatible with the
//! [`num-valid`](crate) abstraction for complex numbers. It implements all required traits,
//! including [`FpScalar`](crate::FpScalar), [`ComplexScalarGetParts`](crate::functions::ComplexScalarGetParts), [`ComplexScalarSetParts`](crate::functions::ComplexScalarSetParts), and
//! [`ComplexScalarMutateParts`](crate::functions::ComplexScalarMutateParts), by delegating to the methods of `num::Complex`.
//!
//! This enables generic code written against `T: ComplexScalar` to operate on
//! `Complex<f64>` values, providing a performant backend for complex arithmetic.
//!
//! ## Core Components
//!
//! - **`Native64`**: A marker struct that implements the [`RawKernel`](crate::core::traits::RawKernel) trait. It is used
//!   in generic contexts to select this native kernel, specifying [`f64`] as its
//!   [`RawReal`](crate::core::traits::RawKernel::RawReal) type and [`num::Complex<f64>`](num::Complex) as its
//!   [`RawComplex`](crate::core::traits::RawKernel::RawComplex) type.
//! - **Trait Implementations**: This module is primarily composed of `impl` blocks that
//!   satisfy the contracts of core traits ([`FpScalar`](crate::FpScalar), [`RealScalar`](crate::RealScalar), [`ComplexScalar`](crate::ComplexScalar),
//!   [`Arithmetic`](crate::functions::Arithmetic), [`MulAddRef`](crate::MulAddRef), etc.) for `f64` and `Complex<f64>`.
//!
//! ## Validation
//!
//! It is crucial to understand that the base types `f64` and `Complex<f64>` do not
//! inherently enforce properties like finiteness (they can be `NaN` or `Infinity`).
//!
//! The [`num-valid`](crate) library introduces validation at the **trait and wrapper level**,
//! not at the base type level. For instance, [`RealScalar::try_from_f64`](crate::RealScalar::try_from_f64) for `f64`
//! uses a [`StrictFinitePolicy`](crate::core::policies::StrictFinitePolicy) to ensure the input is finite before creating an instance.
//! This design separates the raw, high-performance types from the validated, safer
//! abstractions built on top of them.
//!
//! For scenarios requiring types that are guaranteed to be valid by construction,
//! consider using the validated wrappers from the [`validated`](crate::backends::native64::validated) module.

use crate::{
    ComplexScalar, Constants, FpScalar, MulAddRef, RealScalar,
    core::{
        errors::{
            ErrorsRawRealToInteger, ErrorsTryFromf64, ErrorsValidationRawComplex,
            ErrorsValidationRawReal, capture_backtrace,
        },
        policies::{Native64RawRealStrictFinitePolicy, StrictFinitePolicy, validate_complex},
        traits::{RawKernel, validation::ValidationPolicyReal},
    },
    functions::{
        Clamp, Classify, ExpM1, Hypot, Ln1p, Rounding, Sign, TotalCmp,
        complex::{
            ComplexScalarConstructors, ComplexScalarGetParts, ComplexScalarMutateParts,
            ComplexScalarSetParts,
        },
    },
    kernels::{
        RawComplexTrait, RawRealTrait, RawScalarHyperbolic, RawScalarPow, RawScalarTrait,
        RawScalarTrigonometric,
    },
    scalar_kind,
};
use az::CheckedAs;
use duplicate::duplicate_item;
use num::{Complex, Zero};
use num_traits::{MulAdd, MulAddAssign};
use std::{
    cmp::Ordering,
    hash::{Hash, Hasher},
    num::FpCategory,
};
use try_create::ValidationPolicy;

//----------------------------------------------------------------------------------------------
/// Numerical kernel specifier for Rust's native 64-bit floating-point types.
///
/// This struct is used as a generic argument or associated type to indicate
/// that the floating-point values for computations should be [`f64`] for real numbers
/// and [`num::Complex<f64>`] for complex numbers.
///
/// It implements the [`RawKernel`] trait, bridging the native raw types to the
/// [`num-valid`](crate)'s generic numerical abstraction.
#[derive(Debug, Clone, PartialEq, PartialOrd)]
pub struct Native64;

impl RawKernel for Native64 {
    /// The type for a real scalar value in this numerical kernel.
    type RawReal = f64;

    /// The type for a complex scalar value in this numerical kernel.
    type RawComplex = Complex<f64>;
}

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

//----------------------------------------------------------------------------------------------
/// Implements the [`FpScalar`] trait for [`f64`].
///
/// This trait provides a common interface for floating-point scalar types within
/// the [`num-valid`](crate) ecosystem.
impl FpScalar for f64 {
    type Kind = scalar_kind::Real;

    /// Defines the associated real type, which is [`f64`] itself.
    type RealType = f64;

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

/// Implements the [`FpScalar`] trait for [`num::Complex<f64>`].
///
/// This trait provides a common interface for floating-point scalar types within
/// the [`num-valid`](crate) ecosystem.
impl FpScalar for Complex<f64> {
    type Kind = scalar_kind::Complex;

    /// Defines the associated real type for complex numbers, which is [`f64`].
    type RealType = f64;

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

//----------------------------------------------------------------------------------------------
impl Sign for f64 {
    /// Returns a number with the magnitude of `self` and the sign of `sign`.
    #[inline(always)]
    fn kernel_copysign(self, sign: &Self) -> Self {
        self.copysign(*sign)
    }

    /// Returns `true` if the value is negative, −0 or NaN with a negative sign.
    #[inline(always)]
    fn kernel_is_sign_negative(&self) -> bool {
        self.is_sign_negative()
    }

    /// Returns `true` if the value is positive, +0 or NaN with a positive sign.
    #[inline(always)]
    fn kernel_is_sign_positive(&self) -> bool {
        self.is_sign_positive()
    }

    /// Computes the signum.
    ///
    /// The returned value is:
    /// - `1.0` if the value is positive, +0.0 or +∞
    /// - `−1.0` if the value is negative, −0.0 or −∞
    /// - `NaN` if the value is NaN
    #[inline(always)]
    fn kernel_signum(self) -> Self {
        self.signum()
    }
}

impl Rounding for f64 {
    /// Returns the smallest integer greater than or equal to `self`.
    #[inline(always)]
    fn kernel_ceil(self) -> Self {
        self.ceil()
    }

    /// Returns the largest integer smaller than or equal to `self`.
    #[inline(always)]
    fn kernel_floor(self) -> Self {
        self.floor()
    }

    /// Returns the fractional part of `self`.
    #[inline(always)]
    fn kernel_fract(self) -> Self {
        self.fract()
    }

    /// Rounds `self` to the nearest integer, rounding half-way cases away from zero.
    #[inline(always)]
    fn kernel_round(self) -> Self {
        self.round()
    }

    /// Returns the nearest integer to a number. Rounds half-way cases to the number with an even least significant digit.
    ///
    /// This function always returns the precise result.
    ///
    /// # Examples
    /// ```
    /// use num_valid::{RealScalar, functions::Rounding};
    ///
    /// let f = 3.3_f64;
    /// let g = -3.3_f64;
    /// let h = 3.5_f64;
    /// let i = 4.5_f64;
    ///
    /// assert_eq!(f.kernel_round_ties_even(), 3.0);
    /// assert_eq!(g.kernel_round_ties_even(), -3.0);
    /// assert_eq!(h.kernel_round_ties_even(), 4.0);
    /// assert_eq!(i.kernel_round_ties_even(), 4.0);
    /// ```
    #[inline(always)]
    fn kernel_round_ties_even(self) -> Self {
        self.round_ties_even()
    }

    /// Returns the integer part of `self`. This means that non-integer numbers are always truncated towards zero.
    ///    
    /// # Examples
    /// ```
    /// use num_valid::{RealScalar, functions::Rounding};
    ///
    /// let f = 3.7_f64;
    /// let g = 3.0_f64;
    /// let h = -3.7_f64;
    ///
    /// assert_eq!(f.kernel_trunc(), 3.0);
    /// assert_eq!(g.kernel_trunc(), 3.0);
    /// assert_eq!(h.kernel_trunc(), -3.0);
    /// ```
    #[inline(always)]
    fn kernel_trunc(self) -> Self {
        self.trunc()
    }
}

impl Constants for f64 {
    /// [Machine epsilon] value for `f64`.
    ///
    /// This is the difference between `1.0` and the next larger representable number.
    ///
    /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon
    #[inline(always)]
    fn epsilon() -> Self {
        f64::EPSILON
    }

    /// Build and return the (floating point) value -1. represented by a `f64`.
    #[inline(always)]
    fn negative_one() -> Self {
        -1.
    }

    /// Build and return the (floating point) value 0.5 represented by the proper type.
    #[inline(always)]
    fn one_div_2() -> Self {
        0.5
    }

    /// Build and return the (floating point) value `2.0`.
    #[inline(always)]
    fn two() -> Self {
        2.
    }

    /// Build and return the maximum finite value allowed by the current floating point representation.
    #[inline(always)]
    fn max_finite() -> Self {
        f64::MAX
    }

    /// Build and return the minimum finite (i.e., the most negative) value allowed by the current floating point representation.
    #[inline(always)]
    fn min_finite() -> Self {
        f64::MIN
    }

    /// Build and return the (floating point) value `Ï€`.
    #[inline(always)]
    fn pi() -> Self {
        std::f64::consts::PI
    }

    /// Build and return the (floating point) value `2 π`.
    #[inline(always)]
    fn two_pi() -> Self {
        std::f64::consts::PI * 2.
    }

    /// Build and return the (floating point) value `Ï€/2`.
    #[inline(always)]
    fn pi_div_2() -> Self {
        std::f64::consts::FRAC_PI_2
    }

    /// Build and return the natural logarithm of 2, i.e. the (floating point) value `ln(2)`.
    #[inline(always)]
    fn ln_2() -> Self {
        std::f64::consts::LN_2
    }

    /// Build and return the natural logarithm of 10, i.e. the (floating point) value `ln(10)`.
    #[inline(always)]
    fn ln_10() -> Self {
        std::f64::consts::LN_10
    }

    /// Build and return the base-10 logarithm of 2, i.e. the (floating point) value `Log_10(2)`.
    #[inline(always)]
    fn log10_2() -> Self {
        std::f64::consts::LOG10_2
    }

    /// Build and return the base-2 logarithm of 10, i.e. the (floating point) value `Log_2(10)`.
    #[inline(always)]
    fn log2_10() -> Self {
        std::f64::consts::LOG2_10
    }

    /// Build and return the base-2 logarithm of `e`, i.e. the (floating point) value `Log_2(e)`.
    #[inline(always)]
    fn log2_e() -> Self {
        std::f64::consts::LOG2_E
    }

    /// Build and return the base-10 logarithm of `e`, i.e. the (floating point) value `Log_10(e)`.
    #[inline(always)]
    fn log10_e() -> Self {
        std::f64::consts::LOG10_E
    }

    /// Build and return the (floating point) value `e` represented by the proper type.
    #[inline(always)]
    fn e() -> Self {
        std::f64::consts::E
    }
}

impl Clamp for f64 {
    /// Clamp the value within the specified bounds.
    ///
    /// Returns `max` if `self` is greater than `max`, and `min` if `self` is less than `min`.
    /// Otherwise this returns `self`.
    ///
    /// Note that this function returns `NaN` if the initial value was `NaN` as well.
    ///
    /// # Panics
    /// Panics if `min` > `max`, `min` is `NaN`, or `max` is `NaN`.
    /// ```
    /// use num_valid::functions::Clamp;
    ///
    /// assert!(Clamp::clamp_ref(-3.0f64, &-2.0, &1.0) == -2.0);
    /// assert!(Clamp::clamp_ref(0.0f64, &-2.0, &1.0) == 0.0);
    /// assert!(Clamp::clamp_ref(2.0f64, &-2.0, &1.0) == 1.0);
    /// assert!(Clamp::clamp_ref(f64::NAN, &-2.0, &1.0).is_nan());
    /// ```
    #[inline(always)]
    fn clamp_ref(self, min: &Self, max: &Self) -> Self {
        f64::clamp(self, *min, *max)
    }
}

impl Classify for f64 {
    /// Returns the floating point category of the number. If only one property is going to be tested,
    /// it is generally faster to use the specific predicate instead.
    /// ```
    /// use num_valid::functions::Classify;
    /// use std::num::FpCategory;
    ///
    /// let num = 12.4_f64;
    /// let inf = f64::INFINITY;
    ///
    /// assert_eq!(Classify::classify(&num), FpCategory::Normal);
    /// assert_eq!(Classify::classify(&inf), FpCategory::Infinite);
    /// ```
    #[inline(always)]
    fn classify(&self) -> FpCategory {
        f64::classify(*self)
    }
}

impl ExpM1 for f64 {
    /// Returns `e^(self) - 1`` in a way that is accurate even if the number is close to zero.
    #[inline(always)]
    fn exp_m1(self) -> Self {
        f64::exp_m1(self)
    }
}

impl Hypot for f64 {
    /// Compute the distance between the origin and a point (`self`, `other`) on the Euclidean plane.
    /// Equivalently, compute the length of the hypotenuse of a right-angle triangle with other sides having length `self.abs()` and `other.abs()`.
    #[inline(always)]
    fn hypot(self, other: &Self) -> Self {
        f64::hypot(self, *other)
    }
}

impl Ln1p for f64 {
    /// Returns `ln(1. + self)` (natural logarithm) more accurately than if the operations were performed separately.
    #[inline(always)]
    fn ln_1p(self) -> Self {
        f64::ln_1p(self)
    }
}

impl TotalCmp for f64 {
    #[inline(always)]
    fn total_cmp(&self, other: &Self) -> Ordering {
        self.total_cmp(other)
    }
}

impl RealScalar for f64 {
    type RawReal = f64;

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

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

    /// Try to build a [`f64`] instance from a [`f64`].
    /// The returned value is `Ok` if the input `value` is finite,
    /// otherwise the returned value is `ErrorsTryFromf64`.
    #[inline(always)]
    fn try_from_f64(value: f64) -> Result<Self, ErrorsTryFromf64<f64>> {
        StrictFinitePolicy::<f64, 53>::validate(value)
            .map_err(|e| ErrorsTryFromf64::Output { source: e })
    }
}

impl ComplexScalarConstructors for Complex<f64> {
    type RawComplex = Complex<f64>;

    fn try_new_complex(
        real_part: f64,
        imag_part: f64,
    ) -> Result<Self, ErrorsValidationRawComplex<ErrorsValidationRawReal<f64>>> {
        validate_complex::<Native64RawRealStrictFinitePolicy>(&real_part, &imag_part)
            .map(|_| Complex::new(real_part, imag_part))
    }
}

/// Implement the [`ComplexScalarGetParts`] trait for the `Complex<f64>` type.
impl ComplexScalarGetParts for Complex<f64> {
    /// Get the real part of the complex number.
    #[inline(always)]
    fn real_part(&self) -> f64 {
        self.re
    }

    /// Get the imaginary part of the complex number.
    #[inline(always)]
    fn imag_part(&self) -> f64 {
        self.im
    }

    /// Returns a reference to the raw real part of the complex number.
    #[inline(always)]
    fn raw_real_part(&self) -> &f64 {
        &self.re
    }

    /// Returns a reference to the raw imaginary part of the complex number.
    #[inline(always)]
    fn raw_imag_part(&self) -> &f64 {
        &self.im
    }
}

/// Implement the [`ComplexScalarSetParts`] trait for the `Complex<f64>` type.
impl ComplexScalarSetParts for Complex<f64> {
    /// Set the value of the real part.
    ///
    /// # Panics
    /// In **debug builds**, this will panic if `real_part` is not finite.
    /// This check is disabled in release builds for performance.
    #[inline(always)]
    fn set_real_part(&mut self, real_part: f64) {
        debug_assert!(
            real_part.is_finite(),
            "The real part is not finite (i.e. is infinite or NaN)."
        );
        self.re = real_part;
    }

    /// Set the value of the imaginary part.
    ///
    /// # Panics
    /// In **debug builds**, this will panic if `imag_part` is not finite.
    /// This check is disabled in release builds for performance.
    #[inline(always)]
    fn set_imaginary_part(&mut self, imag_part: f64) {
        debug_assert!(
            imag_part.is_finite(),
            "The imaginary part is not finite (i.e. is infinite or NaN)."
        );
        self.im = imag_part;
    }
}

/// Implement the [`ComplexScalarMutateParts`] trait for the `Complex<f64>` type.
impl ComplexScalarMutateParts for Complex<f64> {
    /// Add the value of the the real coefficient `c` to real part of `self`.
    ///
    /// # Panics
    /// In **debug builds**, this will panic if the real part of `self` is not finite after the addition.
    /// This check is disabled in release builds for performance.
    #[inline(always)]
    fn add_to_real_part(&mut self, c: &f64) {
        self.re += c;

        debug_assert!(
            self.re.is_finite(),
            "The real part is not finite (i.e. is infinite or NaN)."
        );
    }

    /// Add the value of the the real coefficient `c` to imaginary part of `self`.
    ///
    /// # Panics
    /// In **debug builds**, this will panic if the imaginary part of `self` is not finite after the addition.
    /// This check is disabled in release builds for performance.
    #[inline(always)]
    fn add_to_imaginary_part(&mut self, c: &f64) {
        self.im += c;

        debug_assert!(
            self.im.is_finite(),
            "The imaginary part is not finite (i.e. is infinite or NaN)."
        );
    }

    /// Multiply the value of the real part by the real coefficient `c`.
    ///
    /// # Panics
    /// In **debug builds**, this will panic if the real part of `self` is not finite after the multiplication.
    /// This check is disabled in release builds for performance.
    #[inline(always)]
    fn multiply_real_part(&mut self, c: &f64) {
        self.re *= c;

        debug_assert!(
            self.re.is_finite(),
            "The real part is not finite (i.e. is infinite or NaN)."
        );
    }

    /// Multiply the value of the imaginary part by the real coefficient `c`.
    ///
    /// # Panics
    /// In **debug builds**, this will panic if the imaginary part of `self` is not finite after the multiplication.
    /// This check is disabled in release builds for performance.
    #[inline(always)]
    fn multiply_imaginary_part(&mut self, c: &f64) {
        self.im *= c;

        debug_assert!(
            self.im.is_finite(),
            "The imaginary part is not finite (i.e. is infinite or NaN)."
        );
    }
}

/// Implement the [`ComplexScalar`] trait for the `Complex<f64>` type.
impl ComplexScalar for Complex<f64> {
    fn into_parts(self) -> (Self::RealType, Self::RealType) {
        (self.re, self.im)
    }
}

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

//----------------------------------------------------------------------------------------------
#[duplicate_item(
    T trait_comment;
    [f64] ["Implementation of the [`MulAddRef`] trait for `f64`."];
    [Complex<f64>] ["Implementation of the [`MulAddRef`] trait for `Complex<f64>`."];
)]
#[doc = trait_comment]
impl MulAddRef for T {
    /// Multiplies and adds in one fused operation, rounding to the nearest with only one rounding error.
    ///
    /// `a.mul_add(b, c)` produces a result like `a * &b + &c`.
    #[inline(always)]
    fn mul_add_ref(self, b: &Self, c: &Self) -> Self {
        <Self as num::traits::MulAdd>::mul_add(self, *b, *c)
    }
}
//----------------------------------------------------------------------------------------------

// =============================================================================
// Implementations for f64 and Complex<f64>
// =============================================================================

#[duplicate_item(
    T;
    [f64];
    [Complex::<f64>];
)]
impl RawScalarTrigonometric for T {
    #[duplicate_item(
        unchecked_method method;
        [unchecked_sin]  [sin];
        [unchecked_asin] [asin];
        [unchecked_cos]  [cos];
        [unchecked_acos] [acos];
        [unchecked_tan]  [tan];
        [unchecked_atan] [atan];
    )]
    #[inline(always)]
    fn unchecked_method(self) -> Self {
        T::method(self)
    }
}

#[duplicate_item(
    T;
    [f64];
    [Complex::<f64>];
)]
impl RawScalarHyperbolic for T {
    #[duplicate_item(
        unchecked_method  method;
        [unchecked_sinh]  [sinh];
        [unchecked_asinh] [asinh];
        [unchecked_cosh]  [cosh];
        [unchecked_acosh] [acosh];
        [unchecked_tanh]  [tanh];
        [unchecked_atanh] [atanh];
    )]
    #[inline(always)]
    fn unchecked_method(self) -> Self {
        T::method(self)
    }
}

impl RawScalarPow for f64 {
    #[duplicate_item(
        unchecked_method             exponent_type;
        [unchecked_pow_exponent_i8]  [i8];
        [unchecked_pow_exponent_i16] [i16];
        [unchecked_pow_exponent_u8]  [u8];
        [unchecked_pow_exponent_u16] [u16];
    )]
    #[inline(always)]
    fn unchecked_method(self, exponent: &exponent_type) -> f64 {
        f64::powi(self, (*exponent).into())
    }

    #[inline(always)]
    fn unchecked_pow_exponent_i32(self, exponent: &i32) -> Self {
        f64::powi(self, *exponent)
    }

    #[duplicate_item(
        unchecked_method               exponent_type;
        [unchecked_pow_exponent_i64]   [i64];
        [unchecked_pow_exponent_i128]  [i128];
        [unchecked_pow_exponent_isize] [isize];
        [unchecked_pow_exponent_u32]   [u32];
        [unchecked_pow_exponent_u64]   [u64];
        [unchecked_pow_exponent_u128]  [u128];
        [unchecked_pow_exponent_usize] [usize];
    )]
    #[inline(always)]
    fn unchecked_method(self, exponent: &exponent_type) -> f64 {
        f64::powi(
            self,
            (*exponent)
                .try_into()
                .expect("The exponent {exponent} cannot be converted to an integer of type i32"),
        )
    }
}

impl RawScalarTrait for f64 {
    type ValidationErrors = ErrorsValidationRawReal<f64>;

    #[inline(always)]
    fn raw_zero(_precision: u32) -> f64 {
        0.
    }

    #[inline(always)]
    fn is_zero(&self) -> bool {
        <Self as Zero>::is_zero(self)
    }
    #[inline(always)]
    fn raw_one(_precision: u32) -> f64 {
        1.
    }

    #[duplicate_item(
        unchecked_method       method;
        [unchecked_reciprocal] [recip];
        [unchecked_exp]        [exp];
        [unchecked_sqrt]       [sqrt];
        [unchecked_ln]         [ln];
        [unchecked_log2]       [log2];
        [unchecked_log10]      [log10];
    )]
    #[inline(always)]
    fn unchecked_method(self) -> f64 {
        f64::method(self)
    }

    /// Multiplies and adds in one fused operation, rounding to the nearest with only one rounding error.
    ///
    /// `a.mul_add(b, c)` produces a result like `a * &b + &c`.
    #[inline(always)]
    fn unchecked_mul_add(self, b: &Self, c: &Self) -> Self {
        f64::mul_add(self, *b, *c)
    }

    #[inline(always)]
    fn compute_hash<H: Hasher>(&self, state: &mut H) {
        debug_assert!(
            self.is_finite(),
            "Hashing a non-finite f64 value (i.e., NaN or Infinity) may lead to inconsistent results."
        );
        if self == &0.0 {
            // Hash all zeros (positive and negative) to the same value
            0.0f64.to_bits().hash(state);
        } else {
            self.to_bits().hash(state);
        }
    }
}

impl RawRealTrait for f64 {
    type RawComplex = Complex<f64>;

    #[inline(always)]
    fn unchecked_abs(self) -> f64 {
        f64::abs(self)
    }

    #[inline(always)]
    fn unchecked_atan2(self, denominator: &Self) -> Self {
        f64::atan2(self, *denominator)
    }

    #[inline(always)]
    fn unchecked_pow_exponent_real(self, exponent: &Self) -> Self {
        f64::powf(self, *exponent)
    }

    #[inline(always)]
    fn unchecked_hypot(self, other: &Self) -> Self {
        f64::hypot(self, *other)
    }

    #[inline(always)]
    fn unchecked_ln_1p(self) -> Self {
        f64::ln_1p(self)
    }

    #[inline(always)]
    fn unchecked_exp_m1(self) -> Self {
        f64::exp_m1(self)
    }

    /// Multiplies two pairs and adds them in one fused operation, rounding to the nearest with only one rounding error.
    /// `a.unchecked_mul_add_mul_mut(&b, &c, &d)` produces a result like `&a * &b + &c * &d`, but stores the result in `a` using its precision.
    #[inline(always)]
    fn unchecked_mul_add_mul_mut(&mut self, mul: &Self, add_mul1: &Self, add_mul2: &Self) {
        self.mul_add_assign(*mul, add_mul1 * add_mul2);
    }

    /// Multiplies two pairs and subtracts them in one fused operation, rounding to the nearest with only one rounding error.
    /// `a.unchecked_mul_sub_mul_mut(&b, &c, &d)` produces a result like `&a * &b - &c * &d`, but stores the result in `a` using its precision.
    #[inline(always)]
    fn unchecked_mul_sub_mul_mut(&mut self, mul: &Self, sub_mul1: &Self, sub_mul2: &Self) {
        self.mul_add_assign(*mul, -sub_mul1 * sub_mul2);
    }

    #[inline(always)]
    fn raw_total_cmp(&self, other: &Self) -> Ordering {
        f64::total_cmp(self, other)
    }

    /// Clamps the value within the specified bounds.
    #[inline(always)]
    fn raw_clamp(self, min: &Self, max: &Self) -> Self {
        f64::clamp(self, *min, *max)
    }

    #[inline(always)]
    fn raw_classify(&self) -> FpCategory {
        f64::classify(*self)
    }

    #[inline(always)]
    fn raw_two(_precision: u32) -> Self {
        2.
    }

    #[inline(always)]
    fn raw_one_div_2(_precision: u32) -> Self {
        0.5
    }

    #[inline(always)]
    fn raw_pi(_precision: u32) -> Self {
        std::f64::consts::PI
    }

    #[inline(always)]
    fn raw_two_pi(_precision: u32) -> Self {
        2. * std::f64::consts::PI
    }

    #[inline(always)]
    fn raw_pi_div_2(_precision: u32) -> Self {
        std::f64::consts::FRAC_PI_2
    }

    #[inline(always)]
    fn raw_max_finite(_precision: u32) -> Self {
        f64::MAX
    }

    #[inline(always)]
    fn raw_min_finite(_precision: u32) -> Self {
        f64::MIN
    }

    #[inline(always)]
    fn raw_epsilon(_precision: u32) -> Self {
        f64::EPSILON
    }

    #[inline(always)]
    fn raw_ln_2(_precision: u32) -> Self {
        std::f64::consts::LN_2
    }

    #[inline(always)]
    fn raw_ln_10(_precision: u32) -> Self {
        std::f64::consts::LN_10
    }

    #[inline(always)]
    fn raw_log10_2(_precision: u32) -> Self {
        std::f64::consts::LOG10_2
    }

    #[inline(always)]
    fn raw_log2_10(_precision: u32) -> Self {
        std::f64::consts::LOG2_10
    }

    #[inline(always)]
    fn raw_log2_e(_precision: u32) -> Self {
        std::f64::consts::LOG2_E
    }

    #[inline(always)]
    fn raw_log10_e(_precision: u32) -> Self {
        std::f64::consts::LOG10_E
    }

    #[inline(always)]
    fn raw_e(_precision: u32) -> Self {
        std::f64::consts::E
    }

    #[inline(always)]
    fn try_new_raw_real_from_f64<RealPolicy: ValidationPolicyReal<Value = Self>>(
        value: f64,
    ) -> Result<Self, ErrorsTryFromf64<f64>> {
        RealPolicy::validate(value).map_err(|e| ErrorsTryFromf64::Output { source: e })
    }

    #[inline(always)]
    fn precision(&self) -> u32 {
        53 // f64 has 53 bits of precision
    }

    #[inline(always)]
    fn truncate_to_usize(self) -> Result<usize, ErrorsRawRealToInteger<f64, usize>> {
        if !self.is_finite() {
            return Err(ErrorsRawRealToInteger::NotFinite {
                value: self,
                backtrace: capture_backtrace(),
            });
        }

        match self.checked_as::<usize>() {
            Some(value) => Ok(value),
            None => Err(ErrorsRawRealToInteger::OutOfRange {
                value: self,
                min: usize::MIN,
                max: usize::MAX,
                backtrace: capture_backtrace(),
            }),
        }
    }
}

impl RawScalarPow for Complex<f64> {
    #[duplicate_item(
        unchecked_method             exponent_type;
        [unchecked_pow_exponent_i8]  [i8];
        [unchecked_pow_exponent_i16] [i16];
    )]
    #[inline(always)]
    fn unchecked_method(self, exponent: &exponent_type) -> Self {
        Complex::<f64>::powi(&self, (*exponent).into())
    }

    #[inline(always)]
    fn unchecked_pow_exponent_i32(self, exponent: &i32) -> Self {
        Complex::<f64>::powi(&self, *exponent)
    }

    #[duplicate_item(
        unchecked_method               exponent_type;
        [unchecked_pow_exponent_i64]   [i64];
        [unchecked_pow_exponent_i128]  [i128];
        [unchecked_pow_exponent_isize] [isize];
    )]
    #[inline(always)]
    fn unchecked_method(self, exponent: &exponent_type) -> Self {
        Complex::<f64>::powi(
            &self,
            (*exponent)
                .try_into()
                .expect("The exponent {exponent} cannot be converted to an integer of type i32"),
        )
    }

    #[duplicate_item(
        unchecked_method             exponent_type;
        [unchecked_pow_exponent_u8]  [u8];
        [unchecked_pow_exponent_u16] [u16];
    )]
    #[inline(always)]
    fn unchecked_method(self, exponent: &exponent_type) -> Self {
        Complex::<f64>::powu(&self, (*exponent).into())
    }

    #[inline(always)]
    fn unchecked_pow_exponent_u32(self, exponent: &u32) -> Self {
        Complex::<f64>::powu(&self, *exponent)
    }

    #[duplicate_item(
        unchecked_method               exponent_type;
        [unchecked_pow_exponent_u64]   [u64];
        [unchecked_pow_exponent_u128]  [u128];
        [unchecked_pow_exponent_usize] [usize];
    )]
    #[inline(always)]
    fn unchecked_method(self, exponent: &exponent_type) -> Self {
        Complex::<f64>::powu(
            &self,
            (*exponent)
                .try_into()
                .expect("The exponent {exponent} cannot be converted to an integer of type u32"),
        )
    }
}

impl RawScalarTrait for Complex<f64> {
    type ValidationErrors = ErrorsValidationRawComplex<ErrorsValidationRawReal<f64>>;

    #[inline(always)]
    fn raw_zero(_precision: u32) -> Self {
        Complex::new(0., 0.)
    }

    #[inline(always)]
    fn is_zero(&self) -> bool {
        <Self as Zero>::is_zero(self)
    }

    #[inline(always)]
    fn raw_one(_precision: u32) -> Self {
        Complex::new(1., 0.)
    }

    #[duplicate_item(
        unchecked_method       method;
        [unchecked_exp]        [exp];
        [unchecked_sqrt]       [sqrt];
        [unchecked_ln]         [ln];
        [unchecked_log10]      [log10];
    )]
    #[inline(always)]
    fn unchecked_method(self) -> Self {
        Complex::<f64>::method(self)
    }

    #[inline(always)]
    fn unchecked_reciprocal(self) -> Self {
        Complex::<f64>::inv(&self)
    }

    #[inline(always)]
    fn unchecked_log2(self) -> Self {
        Complex::<f64>::ln(self) / std::f64::consts::LN_2
    }

    /// Multiplies and adds in one fused operation, rounding to the nearest with only one rounding error.
    ///
    /// `a.mul_add(b, c)` produces a result like `a * &b + &c`.
    #[inline(always)]
    fn unchecked_mul_add(self, b: &Self, c: &Self) -> Self {
        Complex::<f64>::mul_add(self, *b, *c)
    }

    fn compute_hash<H: Hasher>(&self, state: &mut H) {
        RawComplexTrait::raw_real_part(self).compute_hash(state);
        RawComplexTrait::raw_imag_part(self).compute_hash(state);
    }
}

impl RawComplexTrait for Complex<f64> {
    type RawReal = f64;

    fn new_unchecked_raw_complex(real: f64, imag: f64) -> Self {
        Complex::<f64>::new(real, imag)
    }

    /// Returns a mutable reference to the real part of the complex number.
    fn mut_raw_real_part(&mut self) -> &mut f64 {
        &mut self.re
    }

    /// Returns a mutable reference to the imaginary part of the complex number.
    fn mut_raw_imag_part(&mut self) -> &mut f64 {
        &mut self.im
    }

    #[inline(always)]
    fn unchecked_abs(self) -> f64 {
        Complex::<f64>::norm(self)
    }

    #[inline(always)]
    fn raw_real_part(&self) -> &f64 {
        &self.re
    }

    #[inline(always)]
    fn raw_imag_part(&self) -> &f64 {
        &self.im
    }

    #[inline(always)]
    fn unchecked_arg(self) -> f64 {
        Complex::<f64>::arg(self)
    }

    #[inline(always)]
    fn unchecked_pow_exponent_real(self, exponent: &f64) -> Self {
        Complex::<f64>::powf(self, *exponent)
    }
}

#[cfg(test)]
mod tests {
    use crate::{
        core::errors::{ErrorsValidationRawComplex, ErrorsValidationRawReal},
        functions::TotalCmp,
    };

    mod real {
        use super::*;
        use crate::Constants;

        #[test]
        fn test_constants() {
            assert_eq!(<f64 as Constants>::epsilon(), f64::EPSILON);
            assert_eq!(<f64 as Constants>::negative_one(), -1.0);
            assert_eq!(<f64 as Constants>::one_div_2(), 0.5);
            assert_eq!(<f64 as Constants>::two(), 2.0);
            assert_eq!(<f64 as Constants>::max_finite(), f64::MAX);
            assert_eq!(<f64 as Constants>::min_finite(), f64::MIN);
            assert_eq!(<f64 as Constants>::pi(), std::f64::consts::PI);
            assert_eq!(<f64 as Constants>::two_pi(), std::f64::consts::PI * 2.0);
            assert_eq!(<f64 as Constants>::pi_div_2(), std::f64::consts::FRAC_PI_2);
            assert_eq!(<f64 as Constants>::ln_2(), std::f64::consts::LN_2);
            assert_eq!(<f64 as Constants>::ln_10(), std::f64::consts::LN_10);
            assert_eq!(<f64 as Constants>::log10_2(), std::f64::consts::LOG10_2);
            assert_eq!(<f64 as Constants>::log2_10(), std::f64::consts::LOG2_10);
            assert_eq!(<f64 as Constants>::log2_e(), std::f64::consts::LOG2_E);
            assert_eq!(<f64 as Constants>::log10_e(), std::f64::consts::LOG10_E);
            assert_eq!(<f64 as Constants>::e(), std::f64::consts::E);
        }

        #[test]
        #[allow(clippy::op_ref)]
        fn multiply_ref() {
            let a = 2.0f64;
            let b = 3.0f64;
            let result = a * &b;
            assert_eq!(result, 6.0);
        }

        #[test]
        fn total_cmp() {
            let a = 2.0f64;
            let b = 3.0f64;
            assert_eq!(
                <f64 as TotalCmp>::total_cmp(&a, &b),
                std::cmp::Ordering::Less
            );
            assert_eq!(
                <f64 as TotalCmp>::total_cmp(&b, &a),
                std::cmp::Ordering::Greater
            );
            assert_eq!(
                <f64 as TotalCmp>::total_cmp(&a, &a),
                std::cmp::Ordering::Equal
            );
        }

        mod from_f64 {
            use crate::{RealScalar, backends::native64::validated::RealNative64StrictFinite};

            #[test]
            fn test_from_f64_valid_constants() {
                // Test with mathematical constants (known valid values)
                let pi = RealNative64StrictFinite::from_f64(std::f64::consts::PI);
                assert_eq!(pi.as_ref(), &std::f64::consts::PI);

                let e = RealNative64StrictFinite::from_f64(std::f64::consts::E);
                assert_eq!(e.as_ref(), &std::f64::consts::E);

                let sqrt2 = RealNative64StrictFinite::from_f64(std::f64::consts::SQRT_2);
                assert_eq!(sqrt2.as_ref(), &std::f64::consts::SQRT_2);
            }

            #[test]
            fn test_from_f64_valid_values() {
                // Test with regular valid values
                let x = RealNative64StrictFinite::from_f64(42.0);
                assert_eq!(x.as_ref(), &42.0);

                let y = RealNative64StrictFinite::from_f64(-3.0);
                assert_eq!(y.as_ref(), &-3.0);

                let z = RealNative64StrictFinite::from_f64(0.0);
                assert_eq!(z.as_ref(), &0.0);
            }

            #[test]
            #[should_panic(expected = "RealScalar::from_f64() failed")]
            fn test_from_f64_nan_panics() {
                let _ = RealNative64StrictFinite::from_f64(f64::NAN);
            }

            #[test]
            #[should_panic(expected = "RealScalar::from_f64() failed")]
            fn test_from_f64_infinity_panics() {
                let _ = RealNative64StrictFinite::from_f64(f64::INFINITY);
            }

            #[test]
            #[should_panic(expected = "RealScalar::from_f64() failed")]
            fn test_from_f64_neg_infinity_panics() {
                let _ = RealNative64StrictFinite::from_f64(f64::NEG_INFINITY);
            }

            #[test]
            #[should_panic(expected = "RealScalar::from_f64() failed")]
            fn test_from_f64_subnormal_panics() {
                // Test with a subnormal value (very small but non-zero)
                let _ = RealNative64StrictFinite::from_f64(f64::MIN_POSITIVE / 2.0);
            }

            #[test]
            fn test_try_from_f64_error_handling() {
                // Verify try_from_f64 still works for error handling
                assert!(RealNative64StrictFinite::try_from_f64(f64::NAN).is_err());
                assert!(RealNative64StrictFinite::try_from_f64(f64::INFINITY).is_err());
                assert!(RealNative64StrictFinite::try_from_f64(f64::NEG_INFINITY).is_err());

                // Valid values work with try_from_f64
                assert!(RealNative64StrictFinite::try_from_f64(3.0).is_ok());
                assert!(RealNative64StrictFinite::try_from_f64(0.0).is_ok());
            }
        }

        mod truncate_to_usize {
            use crate::{core::errors::ErrorsRawRealToInteger, kernels::RawRealTrait};

            #[test]
            fn test_f64_truncate_to_usize_valid() {
                assert_eq!(42.0_f64.truncate_to_usize().unwrap(), 42);
                assert_eq!(42.9_f64.truncate_to_usize().unwrap(), 42);
                assert_eq!(0.0_f64.truncate_to_usize().unwrap(), 0);
            }

            #[test]
            fn test_f64_truncate_to_usize_not_finite() {
                assert!(matches!(
                    f64::NAN.truncate_to_usize(),
                    Err(ErrorsRawRealToInteger::NotFinite { .. })
                ));
                assert!(matches!(
                    f64::INFINITY.truncate_to_usize(),
                    Err(ErrorsRawRealToInteger::NotFinite { .. })
                ));
                assert!(matches!(
                    f64::NEG_INFINITY.truncate_to_usize(),
                    Err(ErrorsRawRealToInteger::NotFinite { .. })
                ));
            }

            #[test]
            fn test_f64_truncate_to_usize_out_of_range() {
                // Negative value
                assert!(matches!(
                    (-1.0_f64).truncate_to_usize(),
                    Err(ErrorsRawRealToInteger::OutOfRange { .. })
                ));
                // Value too large
                assert!(matches!(
                    ((usize::MAX as f64) + 1.0).truncate_to_usize(),
                    Err(ErrorsRawRealToInteger::OutOfRange { .. })
                ));

                // this is exactly usize::MAX, which is out of range because f64 cannot represent all integers above 2^53 exactly
                assert!(matches!(
                    (usize::MAX as f64).truncate_to_usize(),
                    Err(ErrorsRawRealToInteger::OutOfRange { .. })
                ));
            }
        }
    }

    mod complex {
        use super::*;
        use crate::{
            ComplexScalarConstructors, ComplexScalarGetParts, ComplexScalarMutateParts,
            ComplexScalarSetParts,
        };
        use num::{Complex, Zero};

        #[test]
        fn real_part() {
            let c1 = Complex::new(1.23, 4.56);
            assert_eq!(c1.real_part(), 1.23);

            let c2 = Complex::new(-7.89, 0.12);
            assert_eq!(c2.real_part(), -7.89);

            let c3 = Complex::new(0.0, 10.0);
            assert_eq!(c3.real_part(), 0.0);

            let c_nan_re = Complex::new(f64::NAN, 5.0);
            assert!(c_nan_re.real_part().is_nan());

            let c_inf_re = Complex::new(f64::INFINITY, 5.0);
            assert!(c_inf_re.real_part().is_infinite());
            assert!(c_inf_re.real_part().is_sign_positive());

            let c_neg_inf_re = Complex::new(f64::NEG_INFINITY, 5.0);
            assert!(c_neg_inf_re.real_part().is_infinite());
            assert!(c_neg_inf_re.real_part().is_sign_negative());
        }

        #[test]
        fn imag_part() {
            let c1 = Complex::new(1.23, 4.56);
            assert_eq!(c1.imag_part(), 4.56);

            let c2 = Complex::new(7.89, -0.12);
            assert_eq!(c2.imag_part(), -0.12);

            let c3 = Complex::new(10.0, 0.0);
            assert_eq!(c3.imag_part(), 0.0);

            let c_nan_im = Complex::new(5.0, f64::NAN);
            assert!(c_nan_im.imag_part().is_nan());

            let c_inf_im = Complex::new(5.0, f64::INFINITY);
            assert!(c_inf_im.imag_part().is_infinite());
            assert!(c_inf_im.imag_part().is_sign_positive());

            let c_neg_inf_im = Complex::new(5.0, f64::NEG_INFINITY);
            assert!(c_neg_inf_im.imag_part().is_infinite());
            assert!(c_neg_inf_im.imag_part().is_sign_negative());
        }

        #[test]
        fn try_new_complex() {
            let r1 = 1.23;
            let i1 = 4.56;
            let c1 = Complex::<f64>::try_new_complex(r1, i1).unwrap();
            assert_eq!(c1.re, r1);
            assert_eq!(c1.im, i1);
            assert_eq!(c1.real_part(), r1);
            assert_eq!(c1.imag_part(), i1);

            let r2 = -7.89;
            let i2 = -0.12;
            let c2 = Complex::<f64>::try_new_complex(r2, i2).unwrap();
            assert_eq!(c2.re, r2);
            assert_eq!(c2.im, i2);
            assert_eq!(c2.real_part(), r2);
            assert_eq!(c2.imag_part(), i2);

            let r3 = 0.0;
            let i3 = 0.0;
            let c3 = Complex::<f64>::try_new_complex(r3, i3).unwrap();
            assert_eq!(c3.re, r3);
            assert_eq!(c3.im, i3);
            assert!(c3.is_zero()); // Assuming Zero trait is available and implemented

            let c_nan_re = Complex::<f64>::try_new_complex(f64::NAN, 5.0).unwrap_err();
            assert!(matches!(
                c_nan_re,
                ErrorsValidationRawComplex::InvalidRealPart { .. }
            ));

            let c_inf_im = Complex::<f64>::try_new_complex(10.0, f64::INFINITY).unwrap_err();
            assert!(matches!(
                c_inf_im,
                ErrorsValidationRawComplex::InvalidImaginaryPart { .. }
            ));

            let c_nan_re_inf_im =
                Complex::<f64>::try_new_complex(f64::NAN, f64::INFINITY).unwrap_err();
            assert!(matches!(
                c_nan_re_inf_im,
                ErrorsValidationRawComplex::InvalidBothParts { .. }
            ));
        }

        #[test]
        fn try_new_pure_real() {
            let r1 = 1.23;
            let c1 = Complex::<f64>::try_new_pure_real(r1).unwrap();
            assert_eq!(c1.re, r1);
            assert_eq!(c1.im, 0.0);

            let c_nan = Complex::<f64>::try_new_pure_real(f64::NAN).unwrap_err();
            assert!(matches!(
                c_nan,
                ErrorsValidationRawComplex::InvalidRealPart {
                    source: box ErrorsValidationRawReal::IsNaN { .. }
                }
            ));
        }

        #[test]
        fn try_new_pure_imaginary() {
            let i1 = 1.23;
            let c1 = Complex::<f64>::try_new_pure_imaginary(i1).unwrap();
            assert_eq!(c1.re, 0.0);
            assert_eq!(c1.im, i1);

            let c_nan = Complex::<f64>::try_new_pure_imaginary(f64::NAN).unwrap_err();
            assert!(matches!(
                c_nan,
                ErrorsValidationRawComplex::InvalidImaginaryPart {
                    source: box ErrorsValidationRawReal::IsNaN { .. }
                }
            ));
        }

        #[test]
        fn add_to_real_part() {
            let mut c = Complex::new(1.0, 2.0);
            c.add_to_real_part(&3.0);
            assert_eq!(c.re, 4.0);
            assert_eq!(c.im, 2.0);

            c.add_to_real_part(&-5.0);
            assert_eq!(c.re, -1.0);
            assert_eq!(c.im, 2.0);
        }

        #[cfg(debug_assertions)]
        #[test]
        #[should_panic(expected = "The real part is not finite (i.e. is infinite or NaN).")]
        fn add_to_real_part_nan() {
            let mut c = Complex::new(1.0, 2.0);
            c.add_to_real_part(&f64::NAN);
        }

        #[test]
        fn add_to_imaginary_part() {
            let mut c = Complex::new(1.0, 2.0);
            c.add_to_imaginary_part(&3.0);
            assert_eq!(c.re, 1.0);
            assert_eq!(c.im, 5.0);

            c.add_to_imaginary_part(&-4.0);
            assert_eq!(c.re, 1.0);
            assert_eq!(c.im, 1.0);
        }

        #[cfg(debug_assertions)]
        #[test]
        #[should_panic(expected = "The imaginary part is not finite (i.e. is infinite or NaN).")]
        fn add_to_imaginary_part_nan() {
            let mut c = Complex::new(1.0, 2.0);
            c.add_to_imaginary_part(&f64::NAN);
        }

        #[test]
        fn multiply_real_part() {
            let mut c = Complex::new(1.0, 2.0);
            c.multiply_real_part(&3.0);
            assert_eq!(c.re, 3.0);
            assert_eq!(c.im, 2.0);

            c.multiply_real_part(&-2.0);
            assert_eq!(c.re, -6.0);
            assert_eq!(c.im, 2.0);
        }

        #[cfg(debug_assertions)]
        #[test]
        #[should_panic(expected = "The real part is not finite (i.e. is infinite or NaN).")]
        fn multiply_real_part_nan() {
            let mut c = Complex::new(1.0, 2.0);
            c.multiply_real_part(&f64::NAN);
        }

        #[test]
        fn multiply_imaginary_part() {
            let mut c = Complex::new(1.0, 2.0);
            c.multiply_imaginary_part(&3.0);
            assert_eq!(c.re, 1.0);
            assert_eq!(c.im, 6.0);

            c.multiply_imaginary_part(&-0.5);
            assert_eq!(c.re, 1.0);
            assert_eq!(c.im, -3.0);
        }

        #[cfg(debug_assertions)]
        #[test]
        #[should_panic(expected = "The imaginary part is not finite (i.e. is infinite or NaN).")]
        fn multiply_imaginary_part_nan() {
            let mut c = Complex::new(1.0, 2.0);
            c.multiply_imaginary_part(&f64::NAN);
        }

        #[test]
        fn set_real_part() {
            let mut c = Complex::new(1.0, 2.0);
            c.set_real_part(3.0);
            assert_eq!(c.re, 3.0);
            assert_eq!(c.im, 2.0);

            c.set_real_part(-4.0);
            assert_eq!(c.re, -4.0);
            assert_eq!(c.im, 2.0);
        }

        #[cfg(debug_assertions)]
        #[test]
        #[should_panic(expected = "The real part is not finite (i.e. is infinite or NaN).")]
        fn set_real_part_nan() {
            let mut c = Complex::new(1.0, 2.0);
            c.set_real_part(f64::NAN);
        }

        #[test]
        fn set_imaginary_part() {
            let mut c = Complex::new(1.0, 2.0);
            c.set_imaginary_part(3.0);
            assert_eq!(c.re, 1.0);
            assert_eq!(c.im, 3.0);

            c.set_imaginary_part(-4.0);
            assert_eq!(c.re, 1.0);
            assert_eq!(c.im, -4.0);
        }

        #[cfg(debug_assertions)]
        #[test]
        #[should_panic(expected = "The imaginary part is not finite (i.e. is infinite or NaN).")]
        fn set_imaginary_part_nan() {
            let mut c = Complex::new(1.0, 2.0);
            c.set_imaginary_part(f64::NAN);
        }

        #[test]
        #[allow(clippy::op_ref)]
        fn multiply_ref() {
            let c1 = Complex::new(1.0, 2.0);
            let c2 = Complex::new(3.0, 4.0);
            let result = c1 * &c2;
            assert_eq!(result, Complex::new(-5.0, 10.0)); // (1*3 - 2*4) + (1*4 + 2*3)i
        }
    }
}