oxinum-complex 0.1.0

Arbitrary-precision complex numbers for OxiNum (CBig over DBig; Pure Rust, GMP/MPFR-free)
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
//! Arithmetic operator implementations for native [`BigComplex`].
//!
//! Every infallible binary operator — `Add`, `Sub`, `Mul` — provides all four
//! ownership variants (`&T op &T`, `T op T`, `T op &T`, `&T op T`), each
//! producing an owned [`BigComplex`]. The matching `*Assign` traits are wired
//! up for both owned and borrowed right-hand sides, and [`Neg`] is provided for
//! owned and borrowed receivers. Component-wise [`PartialEq`] is also provided.
//!
//! # Complex arithmetic
//!
//! With `a = a_re + a_im·i` and `b = b_re + b_im·i`:
//!
//! ```text
//! a + b = (a_re + b_re) + (a_im + b_im)·i
//! a − b = (a_re − b_re) + (a_im − b_im)·i
//! a · b = (a_re·b_re − a_im·b_im) + (a_re·b_im + a_im·b_re)·i
//! a / b = (a · conj(b)) / |b|²
//!       = (a_re·b_re + a_im·b_im)/|b|² + (a_im·b_re − a_re·b_im)/|b|²·i
//! ```
//!
//! # Why there is no `Div` operator and no `Default`
//!
//! * **No `Div` operator.** Native complex division is intrinsically
//!   precision-and-rounding aware (it must divide by the real `norm_sqr`), so
//!   it cannot be expressed through the precision-free `core::ops::Div`
//!   signature without smuggling in a default precision. Division is therefore
//!   exposed only as the explicit [`BigComplex::checked_div`], which takes
//!   `(prec, mode)` and returns [`OxiNumResult`], surfacing
//!   [`OxiNumError::DivByZero`] for a zero divisor rather than panicking.
//! * **No `Default`.** A `BigComplex` value is meaningless without a chosen
//!   working precision, and there is no single precision the library can pick
//!   that is correct for every caller. Rather than bake in an arbitrary
//!   constant, `Default` is intentionally *not* implemented; callers construct
//!   the additive identity explicitly via [`BigComplex::zero(prec)`].
//!
//! `Add`/`Sub`/`Neg` are infallible because the underlying [`BigFloat`]
//! operators are infallible; `Mul` routes through the private [`mul_core`],
//! which combines the four cross-products with banker's rounding at each
//! component's own precision.

use core::ops::{Add, AddAssign, Mul, MulAssign, Neg, Sub, SubAssign};

use oxinum_core::OxiNumResult;
use oxinum_float::native::RoundingMode;

use super::BigComplex;

impl BigComplex {
    /// The complex product `self · rhs` via the four real cross-products.
    ///
    /// `(a + b·i)(c + d·i) = (a·c − b·d) + (a·d + b·c)·i`.
    ///
    /// Each component is formed with banker's rounding ([`RoundingMode::HalfEven`])
    /// using the infallible reference multiply/add on [`BigFloat`].
    pub(crate) fn mul_core(&self, rhs: &BigComplex) -> BigComplex {
        let a = &self.re;
        let b = &self.im;
        let c = &rhs.re;
        let d = &rhs.im;

        // re = a·c − b·d
        let ac = a * c;
        let bd = b * d;
        let re = &ac - &bd;

        // im = a·d + b·c
        let ad = a * d;
        let bc = b * c;
        let im = &ad + &bc;

        BigComplex { re, im }
    }

    /// The complex quotient `self / rhs` at `prec` bits with the given rounding
    /// mode, computed as `(self · conj(rhs)) / |rhs|²`.
    ///
    /// Returns [`OxiNumError::DivByZero`](oxinum_core::OxiNumError::DivByZero)
    /// when `rhs` is the (component-wise) zero, detected via
    /// [`BigComplex::is_zero`] / a zero `norm_sqr`. This is the no-panic core
    /// shared by [`BigComplex::checked_div`].
    pub(crate) fn div_core(
        &self,
        rhs: &BigComplex,
        prec: u32,
        mode: RoundingMode,
    ) -> OxiNumResult<BigComplex> {
        // Zero-divisor guard: surface DivByZero rather than panicking. The
        // real div_ref below would itself return DivByZero, but checking the
        // norm first gives a single, unambiguous error site.
        if rhs.is_zero() {
            return Err(oxinum_core::OxiNumError::DivByZero);
        }

        let guard = prec.saturating_add(10);

        let a = &self.re;
        let b = &self.im;
        let c = &rhs.re;
        let d = &rhs.im;

        // denominator = c² + d² (real, strictly positive here).
        let denom = rhs.norm_sqr();

        // numerator real part: a·c + b·d
        let ac = a * c;
        let bd = b * d;
        let num_re = &ac + &bd;

        // numerator imag part: b·c − a·d
        let bc = b * c;
        let ad = a * d;
        let num_im = &bc - &ad;

        // `guard` documents the headroom carried by `norm_sqr` / the
        // cross-products (all formed at the operands' own precision, which the
        // callers set >= prec); the final components are delivered at `prec`.
        let _ = guard;
        let re = num_re
            .div_ref_with_mode(&denom, mode)?
            .with_precision(prec, mode);
        let im = num_im
            .div_ref_with_mode(&denom, mode)?
            .with_precision(prec, mode);

        Ok(BigComplex { re, im })
    }

    /// Checked complex division `self / rhs` at `prec` bits.
    ///
    /// This is the public, no-panic division entry point for native complex
    /// values (there is deliberately no `core::ops::Div` impl — see the module
    /// docs). The result components are rounded to `prec` bits with `mode`.
    ///
    /// # Errors
    ///
    /// Returns [`OxiNumError::DivByZero`](oxinum_core::OxiNumError::DivByZero)
    /// if `rhs` is zero.
    ///
    /// # Examples
    ///
    /// ```
    /// use oxinum_complex::native::{BigComplex, RoundingMode};
    /// // (2 + 0i) / (1 + i) = 1 − i.
    /// let num = BigComplex::from_f64(2.0, 0.0, 80).expect("finite");
    /// let den = BigComplex::from_f64(1.0, 1.0, 80).expect("finite");
    /// let q = num
    ///     .checked_div(&den, 80, RoundingMode::HalfEven)
    ///     .expect("non-zero divisor");
    /// assert!((q.re().to_f64() - 1.0).abs() < 1e-12);
    /// assert!((q.im().to_f64() + 1.0).abs() < 1e-12);
    /// ```
    pub fn checked_div(
        &self,
        rhs: &BigComplex,
        prec: u32,
        mode: RoundingMode,
    ) -> OxiNumResult<BigComplex> {
        self.div_core(rhs, prec, mode)
    }
}

// ---------------------------------------------------------------------------
// Add
// ---------------------------------------------------------------------------

impl Add<&BigComplex> for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn add(self, rhs: &BigComplex) -> BigComplex {
        BigComplex {
            re: &self.re + &rhs.re,
            im: &self.im + &rhs.im,
        }
    }
}

impl Add<BigComplex> for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn add(self, rhs: BigComplex) -> BigComplex {
        (&self).add(&rhs)
    }
}

impl Add<&BigComplex> for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn add(self, rhs: &BigComplex) -> BigComplex {
        (&self).add(rhs)
    }
}

impl Add<BigComplex> for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn add(self, rhs: BigComplex) -> BigComplex {
        self.add(&rhs)
    }
}

impl AddAssign<&BigComplex> for BigComplex {
    #[inline]
    fn add_assign(&mut self, rhs: &BigComplex) {
        *self = (&*self).add(rhs);
    }
}

impl AddAssign<BigComplex> for BigComplex {
    #[inline]
    fn add_assign(&mut self, rhs: BigComplex) {
        *self = (&*self).add(&rhs);
    }
}

// ---------------------------------------------------------------------------
// Sub
// ---------------------------------------------------------------------------

impl Sub<&BigComplex> for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn sub(self, rhs: &BigComplex) -> BigComplex {
        BigComplex {
            re: &self.re - &rhs.re,
            im: &self.im - &rhs.im,
        }
    }
}

impl Sub<BigComplex> for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn sub(self, rhs: BigComplex) -> BigComplex {
        (&self).sub(&rhs)
    }
}

impl Sub<&BigComplex> for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn sub(self, rhs: &BigComplex) -> BigComplex {
        (&self).sub(rhs)
    }
}

impl Sub<BigComplex> for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn sub(self, rhs: BigComplex) -> BigComplex {
        self.sub(&rhs)
    }
}

impl SubAssign<&BigComplex> for BigComplex {
    #[inline]
    fn sub_assign(&mut self, rhs: &BigComplex) {
        *self = (&*self).sub(rhs);
    }
}

impl SubAssign<BigComplex> for BigComplex {
    #[inline]
    fn sub_assign(&mut self, rhs: BigComplex) {
        *self = (&*self).sub(&rhs);
    }
}

// ---------------------------------------------------------------------------
// Mul
// ---------------------------------------------------------------------------

impl Mul<&BigComplex> for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn mul(self, rhs: &BigComplex) -> BigComplex {
        self.mul_core(rhs)
    }
}

impl Mul<BigComplex> for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn mul(self, rhs: BigComplex) -> BigComplex {
        self.mul_core(&rhs)
    }
}

impl Mul<&BigComplex> for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn mul(self, rhs: &BigComplex) -> BigComplex {
        self.mul_core(rhs)
    }
}

impl Mul<BigComplex> for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn mul(self, rhs: BigComplex) -> BigComplex {
        self.mul_core(&rhs)
    }
}

impl MulAssign<&BigComplex> for BigComplex {
    #[inline]
    fn mul_assign(&mut self, rhs: &BigComplex) {
        *self = self.mul_core(rhs);
    }
}

impl MulAssign<BigComplex> for BigComplex {
    #[inline]
    fn mul_assign(&mut self, rhs: BigComplex) {
        *self = self.mul_core(&rhs);
    }
}

// ---------------------------------------------------------------------------
// Neg
// ---------------------------------------------------------------------------

impl Neg for &BigComplex {
    type Output = BigComplex;
    #[inline]
    fn neg(self) -> BigComplex {
        BigComplex {
            re: -&self.re,
            im: -&self.im,
        }
    }
}

impl Neg for BigComplex {
    type Output = BigComplex;
    #[inline]
    fn neg(self) -> BigComplex {
        (&self).neg()
    }
}

// ---------------------------------------------------------------------------
// PartialEq — component-wise (no Eq: BigFloat is not Eq because of NaN).
// ---------------------------------------------------------------------------

impl PartialEq for BigComplex {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.re == other.re && self.im == other.im
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    const PREC: u32 = 80;
    const MODE: RoundingMode = RoundingMode::HalfEven;

    fn c(re: f64, im: f64) -> BigComplex {
        BigComplex::from_f64(re, im, PREC).expect("finite parts")
    }

    #[test]
    fn add_sub_componentwise() {
        let z = &c(1.0, 2.0) + &c(3.0, -4.0);
        assert!((z.re().to_f64() - 4.0).abs() < 1e-12);
        assert!((z.im().to_f64() + 2.0).abs() < 1e-12);

        let w = &c(1.0, 2.0) - &c(3.0, -4.0);
        assert!((w.re().to_f64() + 2.0).abs() < 1e-12);
        assert!((w.im().to_f64() - 6.0).abs() < 1e-12);
    }

    #[test]
    fn mul_basic() {
        // (1 + 2i)(3 + 4i) = -5 + 10i
        let z = &c(1.0, 2.0) * &c(3.0, 4.0);
        assert!(
            (z.re().to_f64() + 5.0).abs() < 1e-12,
            "re = {}",
            z.re().to_f64()
        );
        assert!(
            (z.im().to_f64() - 10.0).abs() < 1e-12,
            "im = {}",
            z.im().to_f64()
        );
    }

    #[test]
    fn mul_i_squared() {
        // (1 + i)² = 2i
        let one_plus_i = c(1.0, 1.0);
        let z = &one_plus_i * &one_plus_i;
        assert!(z.re().to_f64().abs() < 1e-12, "re = {}", z.re().to_f64());
        assert!(
            (z.im().to_f64() - 2.0).abs() < 1e-12,
            "im = {}",
            z.im().to_f64()
        );
    }

    #[test]
    fn checked_div_basic() {
        // (2 + 0i) / (1 + i) = 1 − i
        let q = c(2.0, 0.0)
            .checked_div(&c(1.0, 1.0), PREC, MODE)
            .expect("non-zero divisor");
        assert!(
            (q.re().to_f64() - 1.0).abs() < 1e-12,
            "re = {}",
            q.re().to_f64()
        );
        assert!(
            (q.im().to_f64() + 1.0).abs() < 1e-12,
            "im = {}",
            q.im().to_f64()
        );
    }

    #[test]
    fn checked_div_general() {
        // (1 + 2i)/(3 + 4i) = (11 + 2i)/25 = 0.44 + 0.08i
        let q = c(1.0, 2.0)
            .checked_div(&c(3.0, 4.0), PREC, MODE)
            .expect("non-zero divisor");
        assert!(
            (q.re().to_f64() - 0.44).abs() < 1e-12,
            "re = {}",
            q.re().to_f64()
        );
        assert!(
            (q.im().to_f64() - 0.08).abs() < 1e-12,
            "im = {}",
            q.im().to_f64()
        );
    }

    #[test]
    fn checked_div_by_zero_is_err() {
        let q = c(1.0, 1.0).checked_div(&BigComplex::zero(PREC), PREC, MODE);
        assert!(
            matches!(q, Err(oxinum_core::OxiNumError::DivByZero)),
            "expected DivByZero, got {q:?}"
        );
    }

    #[test]
    fn neg_and_assign_ops() {
        let z = -&c(1.0, -2.0);
        assert!((z.re().to_f64() + 1.0).abs() < 1e-12);
        assert!((z.im().to_f64() - 2.0).abs() < 1e-12);

        let mut a = c(1.0, 1.0);
        a += &c(2.0, 3.0);
        assert!((a.re().to_f64() - 3.0).abs() < 1e-12);
        assert!((a.im().to_f64() - 4.0).abs() < 1e-12);

        let mut b = c(5.0, 5.0);
        b -= c(1.0, 2.0);
        assert!((b.re().to_f64() - 4.0).abs() < 1e-12);
        assert!((b.im().to_f64() - 3.0).abs() < 1e-12);

        let mut m = c(1.0, 2.0);
        m *= &c(3.0, 4.0);
        assert!((m.re().to_f64() + 5.0).abs() < 1e-12);
        assert!((m.im().to_f64() - 10.0).abs() < 1e-12);
    }

    #[test]
    fn partial_eq_componentwise() {
        assert_eq!(c(1.0, 2.0), c(1.0, 2.0));
        assert_ne!(c(1.0, 2.0), c(1.0, 2.5));
    }
}