rustr/
complex.rs

1//! R Rcomplex methods
2//!
3//!
4
5use rdll::Rcomplex;
6use std::ops::*;
7use std::fmt::{Debug, Formatter, Result};
8use std::cmp::PartialEq;
9
10impl Add for Rcomplex {
11    type Output=Rcomplex;
12    #[inline]
13    fn add(self, rhs: Rcomplex) -> Rcomplex {
14        Rcomplex {
15            r: (self.r + rhs.r),
16            i: (self.i + rhs.i),
17        }
18    }
19}
20
21impl Sub for Rcomplex {
22    type Output=Rcomplex;
23    #[inline]
24    fn sub(self, rhs: Rcomplex) -> Rcomplex {
25        Rcomplex {
26            r: (self.r - rhs.r),
27            i: (self.i - rhs.i),
28        }
29    }
30}
31
32impl Neg for Rcomplex {
33    type Output=Rcomplex;
34    #[inline]
35    fn neg(self) -> Rcomplex {
36        Rcomplex {
37            r: -self.r,
38            i: -self.i,
39        }
40    }
41}
42
43impl Not for Rcomplex {
44    type Output=bool;
45    #[inline]
46    fn not(self) -> bool {
47        (self.r != 0.0) && (self.i != 0.0)
48    }
49}
50
51impl Debug for Rcomplex {
52    #[inline]
53    fn fmt(&self, f: &mut Formatter) -> Result {
54        write!(f, "({}+{}i)", self.r, self.i)
55    }
56}
57
58impl PartialEq for Rcomplex {
59    #[inline]
60    fn eq(&self, other: &Rcomplex) -> bool {
61        self.i == other.i && self.r == other.r
62    }
63}
64
65
66impl Div for Rcomplex {
67    type Output=Rcomplex;
68    #[inline]
69    fn div(self, rhs: Rcomplex) -> Rcomplex {
70
71        let abr = if rhs.r < 0.0 {
72            -rhs.r
73        } else {
74            rhs.r
75        };
76        let abis = if rhs.i < 0.0 {
77            -rhs.i
78        } else {
79            rhs.i
80        };
81        let ratio: ::std::os::raw::c_double;
82        let den: ::std::os::raw::c_double;
83
84        if abr <= abis {
85            ratio = rhs.r / rhs.i;
86            den = rhs.i * (1.0 + ratio * ratio);
87            Rcomplex {
88                r: (self.r * ratio + self.i) / den,
89                i: (self.i * ratio - self.r) / den,
90            }
91        } else {
92            ratio = rhs.i / rhs.r;
93            den = rhs.r * (1.0 + ratio * ratio);
94            Rcomplex {
95                r: (self.r + self.i * ratio) / den,
96                i: (self.i - self.r * ratio) / den,
97            }
98        }
99
100    }
101}