complex-stuff 1.0.0

A library for working with complex numbers in rust
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
//! `complex-stuff` is a collection of utilities to make calculations with complex numbers easy.
//!
//! # Examples
//!
//! ```
//! use complex_stuff::{Complex, ComplexCartesian, ComplexPolar};
//! use std::f64::consts::PI;
//!
//! // Some of the most important operations:
//! fn main() {
//!     // Declare complex numbers with their cartesian or polar form.
//!     let c1 = Complex::new_cartesian(5.0, 3.0);
//!     let c2 = Complex::new_polar(7.0, PI / 4.0);
//!
//!     // Basic arethmetic operations should work as expected.
//!     let sum = c1 + c2;
//!     let diff = c1 - c2;
//!
//!     let prod = c1 * c2;
//!
//!     // All operations which can result in undefined or infinite values
//!     // return a `Option` and need to be handled.
//!
//!     let quot = (c1 / c2)?;
//!
//!     let sqr = c1.pow(Complex::new_real(2.0))?;
//!     let sqrt = c1.root(Complex::new_real(2.0))?;
//!
//!     let log10 = c1.log(Complex::new_real(10.0))?;
//!     
//!     let sin = c1.sin()?;
//!     let cos = c1.cos()?;
//! }
//! ```

use std::{
    f64::consts::E,
    ops::{Add, Div, Mul, Neg, Sub},
};

#[derive(Debug, Clone, Copy)]
/// Descibes a complex number in cartesion form _`re` + `im`i_.
pub struct ComplexCartesian {
    pub re: f64,
    pub im: f64,
}

impl std::fmt::Display for ComplexCartesian {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{} + {}i", self.re, self.im)
    }
}

impl ComplexCartesian {
    /// Converts a complex number from polar to cartesion form.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use complex_stuff::{ComplexCartesian, ComplexPolar};
    ///
    /// let polar = ComplexPolar { mag: 5.0, ang: PI / 2.0 };
    /// let cartesian = ComplexCartesian::from_polar(&polar);
    /// ```
    pub fn from_polar(polar: &ComplexPolar) -> Self {
        let re = polar.mag * polar.ang.cos();
        let im = polar.mag * polar.ang.sin();
        return Self { re, im };
    }
}

#[derive(Debug, Clone, Copy)]
/// Describes a complex number in polar form _`mag`e^(`ang`i)_
pub struct ComplexPolar {
    pub mag: f64,
    pub ang: f64,
}

impl std::fmt::Display for ComplexPolar {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}e^({}i)", self.mag, self.ang)
    }
}

impl ComplexPolar {
    /// Converts a complex number from cartesian to polar form.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::{ComplexCartesian, ComplexPolar};
    ///
    /// let cartesian = ComplexCartesian { re: 5.0, im: 3.0 };
    /// let polar = ComplexPolar::from_cartesian(&cartesian);
    /// ```
    pub fn from_cartesian(cartesian: &ComplexCartesian) -> Self {
        let mag = (cartesian.re * cartesian.re + cartesian.im * cartesian.im).sqrt();
        let ang = (cartesian.re / mag).acos();
        return Self { mag, ang };
    }
}

#[derive(Debug, Clone, Copy)]
/// Describes a complex number in both cartesian and polar form.
pub struct Complex {
    cartesian: ComplexCartesian,
    polar: ComplexPolar,
}

impl std::fmt::Display for Complex {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "Cartesian: {}\nPolar: {}", self.cartesian, self.polar)
    }
}

impl Complex {
    /// Creates a complex number from its cartesian parts.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    /// ```
    pub fn new_cartesian(re: f64, im: f64) -> Self {
        let cartesian = ComplexCartesian { re, im };
        let polar = ComplexPolar::from_cartesian(&cartesian);

        Self { cartesian, polar }
    }

    /// Creates a complex number from its polar parts.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_polar(5.0, PI / 2.0);
    /// ```
    pub fn new_polar(mag: f64, ang: f64) -> Self {
        let polar = ComplexPolar { mag, ang };
        let cartesian = ComplexCartesian::from_polar(&polar);

        Self { cartesian, polar }
    }

    /// Creates a complex number just from its real cartesian part leaving the imaginary part 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_real(5.0);
    ///
    /// assert_eq!(5.0, complex.re());
    /// assert_eq!(0.0, complex.im());
    /// ```
    pub fn new_real(re: f64) -> Self {
        Self::new_cartesian(re, 0.0)
    }

    /// Creates a complex number just from its imaginary cartesian part leaving the real part 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_imaginary(3.0);
    ///
    /// assert_eq!(0.0, complex.re());
    /// assert_eq!(3.0, complex.im());
    /// ```
    pub fn new_imaginary(im: f64) -> Self {
        Self::new_cartesian(0.0, im)
    }

    /// Creates a complex number representing the value 0.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::zero();
    ///
    /// assert_eq!(0.0, complex.re());
    /// assert_eq!(0.0, complex.im());
    /// ```
    pub fn zero() -> Self {
        Self::new_cartesian(0.0, 0.0)
    }

    /// Creates a complex number representing the value 1.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::one();
    ///
    /// assert_eq!(1.0, complex.re());
    /// assert_eq!(0.0, complex.im());
    /// ```
    pub fn one() -> Self {
        Self::new_cartesian(1.0, 0.0)
    }

    /// Creates a complex number representing the value i.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::i();
    ///
    /// assert_eq!(0.0, complex.re());
    /// assert_eq!(1.0, complex.im());
    /// ```
    pub fn i() -> Self {
        Self::new_cartesian(0.0, 1.0)
    }

    /// Creates a complex number representing the value e.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::E;
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::e();
    ///
    /// assert_eq!(E, complex.re());
    /// assert_eq!(0.0, complex.im());
    /// ```
    pub fn e() -> Self {
        Self::new_real(E)
    }
}

impl Complex {
    /// Returns the complex number in cartesian form.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let cartesian = complex.cartesian();
    ///
    /// assert_eq!(5.0, cartesian.re);
    /// assert_eq!(3.0, cartesian.im);
    /// ```
    pub fn cartesian(&self) -> ComplexCartesian {
        self.cartesian
    }

    /// Returns the complex number in polar form.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_polar(5.0, PI / 2.0);
    ///
    /// let polar = complex.polar();
    ///
    /// assert_eq!(5.0, polar.mag);
    /// assert_eq!(PI / 2.0, polar.ang);
    /// ```
    pub fn polar(&self) -> ComplexPolar {
        self.polar
    }

    /// Returns just the real part of the complex numbers cartesian form.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let real = complex.re();
    ///
    /// assert_eq!(5.0, real);
    /// ```
    pub fn re(&self) -> f64 {
        self.cartesian.re
    }

    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let imaginary = complex.im();
    ///
    /// assert_eq!(3.0, imaginary);
    /// ```
    /// Returns just the imaginary part of the complex numbers cartesian form.
    pub fn im(&self) -> f64 {
        self.cartesian.im
    }

    /// Returns just the magnitude of the complex numbers polar form.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_polar(5.0, PI / 2.0);
    ///
    /// let magnitude = complex.mag();
    ///
    /// assert_eq!(5.0, magnitude);
    /// ```
    pub fn mag(&self) -> f64 {
        self.polar.mag
    }

    /// Returns just the angle of the complex numbers polar form.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::f64::consts::PI;
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_polar(5.0, PI / 2.0);
    ///
    /// let angle = complex.ang();
    ///
    /// assert_eq!(PI / 2.0, angle);
    /// ```
    pub fn ang(&self) -> f64 {
        self.polar.ang
    }
}

impl Complex {
    /// Returns the negation of the complex number.
    /// Same as using the unary negation operator `-`.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let opposite = complex.opposite();
    ///
    /// assert_eq!(-5.0, opposite.re());
    /// assert_eq!(-3.0, opposite.im());
    /// ```
    pub fn opposite(self) -> Self {
        let re = -self.cartesian.re;
        let im = -self.cartesian.im;
        Self::new_cartesian(re, im)
    }

    /// Returns the reciprocal of the complex number.
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 0.0);
    ///
    /// let reciprocal = complex.reciprocal();
    /// ```
    pub fn reciprocal(self) -> Option<Self> {
        Self::one() / self
    }
}

impl Neg for Complex {
    type Output = Self;

    fn neg(self) -> Self {
        self.opposite()
    }
}

impl Add for Complex {
    type Output = Self;

    /// Performs the `+` operation.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let c1 = Complex::new_cartesian(5.0, 3.0);
    /// let c2 = Complex::new_cartesian(1.0, 2.0);
    ///
    /// let sum = c1 + c2;
    ///
    /// assert_eq!(6.0, sum.re());
    /// assert_eq!(5.0, sum.im());
    /// ```
    fn add(self, other: Self) -> Self {
        let re = self.cartesian.re + other.cartesian.re;
        let im = self.cartesian.im + other.cartesian.im;

        Self::new_cartesian(re, im)
    }
}

impl Sub for Complex {
    type Output = Self;

    /// Performs the `-` operation.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let c1 = Complex::new_cartesian(5.0, 3.0);
    /// let c2 = Complex::new_cartesian(1.0, 2.0);
    ///
    /// let diff = c1 - c2;
    ///
    /// assert_eq!(4.0, diff.re());
    /// assert_eq!(1.0, diff.im());
    /// ```
    fn sub(self, other: Self) -> Self {
        let re = self.cartesian.re - other.cartesian.re;
        let im = self.cartesian.im - other.cartesian.im;

        Self::new_cartesian(re, im)
    }
}

impl Mul for Complex {
    type Output = Self;

    /// Performs the `*` operation.
    ///
    /// # Examples
    ///
    /// ```
    /// use complex_stuff::Complex;
    ///
    /// let c1 = Complex::new_polar(5.0, 2.0);
    /// let c2 = Complex::new_polar(2.0, 1.0);
    ///
    /// let product = c1 * c2;
    ///
    /// assert_eq!(10.0, product.mag());
    /// assert_eq!(3.0, product.ang());
    /// ```
    fn mul(self, other: Self) -> Self {
        let mag = self.polar.mag * other.polar.mag;
        let ang = self.polar.ang + other.polar.ang;

        Self::new_polar(mag, ang)
    }
}

impl Div for Complex {
    type Output = Option<Self>;

    /// Performs the `/` operation.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let c1 = Complex::new_polar(5.0, 2.0);
    /// let c2 = Complex::new_polar(2.0, 1.0);
    ///
    /// let quotient = (c1 / c2)?;
    ///
    /// assert_eq!(2.5, product.mag());
    /// assert_eq!(1.0, product.ang());
    /// ```
    fn div(self, other: Self) -> Option<Self> {
        if other.polar.mag == 0.0 {
            return None;
        }

        let mag = self.polar.mag / other.polar.mag;
        let ang = self.polar.ang - other.polar.ang;

        Some(Self::new_polar(mag, ang))
    }
}

impl Complex {
    /// Returns the natural logarithm of the complex number.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let result = complex.ln()?;
    /// ```
    pub fn ln(self) -> Option<Self> {
        if self.polar.mag == 0.0 {
            return None;
        }

        let re = self.polar.mag.ln();
        let im = self.polar.ang;

        Some(Self::new_cartesian(re, im))
    }

    /// Returns the logarithm to any other base of the complex number.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    /// let base = Complex::new_cartesian(7.0, 10.0);
    ///
    /// let result = complex.log(base)?;
    /// ```
    pub fn log(self, other: Self) -> Option<Self> {
        if other.polar.mag == 1.0 || self.polar.mag == 0.0 {
            return None;
        }

        if other.polar.mag == 0.0 {
            return Some(Self::zero());
        }

        let mag_s = self.polar.mag;
        let ang_s = self.polar.ang;

        let mag_o = other.polar.mag;
        let ang_o = other.polar.ang;

        let divisor = mag_o.ln().powi(2) + ang_o.powi(2);

        let re = (mag_s.ln() * mag_o.ln() + ang_s * ang_o) / divisor;
        let im = (ang_s * mag_o.ln() - ang_o * mag_s.ln()) / divisor;

        Some(Self::new_cartesian(re, im))
    }
}

impl Complex {
    /// Raises the complex number to any other complex number and returns the result.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    /// let exponent = Complex::new_cartesian(2.0, 1.0);
    ///
    /// let result = complex.pow(exponent)?;
    /// ```
    pub fn pow(self, other: Self) -> Option<Self> {
        if self.polar.mag == 0.0 && other.polar.mag == 0.0 {
            return None;
        }

        if other.polar.mag == 0.0 {
            return Some(Self::one());
        }

        if self.polar.mag == 0.0 {
            return Some(Self::zero());
        }

        let b_mag = self.polar.mag;
        let b_ang = self.polar.ang;

        let e_re = other.cartesian.re;
        let e_im = other.cartesian.im;

        let mag = (e_re * b_mag.ln() - e_im * b_ang).exp();
        let ang = e_re * b_ang + e_im * b_mag.ln();

        Some(Self::new_polar(mag, ang))
    }

    /// Retuns the nth root of the complex number with n being any other complex number.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    /// let n = Complex::new_cartesian(2.0, 1.0);
    ///
    /// let result = complex.root(n)?;
    /// ```
    pub fn root(self, other: Self) -> Option<Self> {
        self.pow(other.reciprocal()?)
    }
}

impl Complex {
    /// Returns the sine of the complex number.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let result = complex.sin()?;
    /// ```
    pub fn sin(self) -> Option<Self> {
        let re = self.cartesian.re.sin() * self.cartesian.im.cosh();
        let im = self.cartesian.re.cos() * self.cartesian.im.sinh();

        Some(Self::new_cartesian(re, im))
    }

    /// Returns the cosine of the complex number.
    ///
    /// Returns `None` when the result is undefined or infinite.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// use complex_stuff::Complex;
    ///
    /// let complex = Complex::new_cartesian(5.0, 3.0);
    ///
    /// let result = complex.cos()?;
    /// ```
    pub fn cos(self) -> Option<Self> {
        let re = self.cartesian.re.cos() * self.cartesian.im.cosh();
        let im = -(self.cartesian.re.sin() * self.cartesian.im.sinh());

        Some(Self::new_cartesian(re, im))
    }
}