oxilean_std/complex/
complex_new_group.rs1use super::complex_type::Complex;
8
9impl Complex {
10 pub fn new(re: f64, im: f64) -> Self {
12 Self { re, im }
13 }
14 pub fn zero() -> Self {
16 Self::new(0.0, 0.0)
17 }
18 pub fn one() -> Self {
20 Self::new(1.0, 0.0)
21 }
22 pub fn i() -> Self {
24 Self::new(0.0, 1.0)
25 }
26 pub fn conj(self) -> Self {
28 Self::new(self.re, -self.im)
29 }
30 pub fn add(self, other: Self) -> Self {
32 Self::new(self.re + other.re, self.im + other.im)
33 }
34 pub fn sub(self, other: Self) -> Self {
36 Self::new(self.re - other.re, self.im - other.im)
37 }
38 pub fn mul(self, other: Self) -> Self {
40 Self::new(
41 self.re * other.re - self.im * other.im,
42 self.re * other.im + self.im * other.re,
43 )
44 }
45 pub fn scale(self, s: f64) -> Self {
47 Self::new(self.re * s, self.im * s)
48 }
49 pub fn neg(self) -> Self {
51 Self::new(-self.re, -self.im)
52 }
53 pub fn exp(self) -> Self {
55 let ea = self.re.exp();
56 Self::new(ea * self.im.cos(), ea * self.im.sin())
57 }
58 pub fn log(self) -> Option<Self> {
60 if self.norm_sq() < f64::EPSILON {
61 return None;
62 }
63 Some(Self::new(self.abs().ln(), self.arg()))
64 }
65 pub fn sqrt(self) -> Self {
67 if self.im == 0.0 && self.re >= 0.0 {
68 return Self::new(self.re.sqrt(), 0.0);
69 }
70 let r = self.abs();
71 let theta = self.arg() / 2.0;
72 Self::new(r.sqrt() * theta.cos(), r.sqrt() * theta.sin())
73 }
74 pub fn sin(self) -> Self {
76 let iz = Self::i().mul(self);
77 let e1 = iz.exp();
78 let e2 = iz.neg().exp();
79 e1.sub(e2).div(Self::new(0.0, 2.0)).unwrap_or(Self::zero())
80 }
81 pub fn from_polar(r: f64, theta: f64) -> Self {
83 Self::new(r * theta.cos(), r * theta.sin())
84 }
85}