oxinum_complex/native/convert.rs
1//! Conversions between native [`BigComplex`] and other numeric types.
2//!
3//! Provides the infallible `From` constructors for the ordered `(re, im)`
4//! [`BigFloat`] pair and for a purely-real [`BigFloat`] (placed on the real
5//! axis, `im = 0` at the real part's precision), plus a lossy projection to a
6//! pair of `f64`s via [`BigFloat::to_f64`].
7
8use oxinum_float::native::BigFloat;
9
10use super::BigComplex;
11
12impl From<(BigFloat, BigFloat)> for BigComplex {
13 /// Build `re + im·i` from the ordered pair `(re, im)`.
14 #[inline]
15 fn from((re, im): (BigFloat, BigFloat)) -> Self {
16 BigComplex::from_parts(re, im)
17 }
18}
19
20impl From<BigFloat> for BigComplex {
21 /// Place a real [`BigFloat`] on the real axis (`im = 0` at `re`'s precision).
22 #[inline]
23 fn from(re: BigFloat) -> Self {
24 BigComplex::from_real(re)
25 }
26}
27
28impl BigComplex {
29 /// Project to a pair of `f64`s `(re, im)` via [`BigFloat::to_f64`].
30 ///
31 /// This is a lossy convenience conversion: each component is rounded to the
32 /// nearest `f64` (and non-finite components map to the corresponding
33 /// `f64::NAN` / `f64::INFINITY`, matching `BigFloat::to_f64`).
34 ///
35 /// # Examples
36 ///
37 /// ```
38 /// use oxinum_complex::native::BigComplex;
39 /// let z = BigComplex::from_f64(1.5, -2.25, 80).expect("finite");
40 /// let (re, im) = z.to_f64_parts();
41 /// assert_eq!(re, 1.5);
42 /// assert_eq!(im, -2.25);
43 /// ```
44 pub fn to_f64_parts(&self) -> (f64, f64) {
45 (self.re().to_f64(), self.im().to_f64())
46 }
47}
48
49// ---------------------------------------------------------------------------
50// Tests
51// ---------------------------------------------------------------------------
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56 use oxinum_float::native::RoundingMode;
57
58 #[test]
59 fn from_pair() {
60 let re = BigFloat::from_f64(2.0, 80).expect("re");
61 let im = BigFloat::from_f64(-3.0, 80).expect("im");
62 let z = BigComplex::from((re, im));
63 assert_eq!(z.re().to_f64(), 2.0);
64 assert_eq!(z.im().to_f64(), -3.0);
65 }
66
67 #[test]
68 fn from_real_axis() {
69 let re = BigFloat::from_i64(7, 80, RoundingMode::HalfEven);
70 let z = BigComplex::from(re);
71 assert_eq!(z.re().to_f64(), 7.0);
72 assert!(z.im().is_zero());
73 }
74
75 #[test]
76 fn to_f64_parts_roundtrip() {
77 let z = BigComplex::from_f64(1.5, -2.25, 80).expect("finite");
78 let (re, im) = z.to_f64_parts();
79 assert_eq!(re, 1.5);
80 assert_eq!(im, -2.25);
81 }
82}