Skip to main content

abels_complex/complex/
polar.rs

1pub type ComplexPolar32 = ComplexPolar<f32>;
2pub type ComplexPolar64 = ComplexPolar<f64>;
3use crate::traits::Number;
4use core::fmt;
5
6use super::Complex as Rectangular;
7use core::ops::*;
8
9/// Creates a complex number in polar form.
10#[inline(always)]
11#[must_use]
12pub const fn complex_polar<FT>(abs: FT, arg: FT) -> ComplexPolar<FT> {
13    ComplexPolar::new(abs, arg)
14}
15
16/// A complex number in polar form.
17#[derive(Clone, Copy, PartialEq, Debug, Default)]
18#[repr(C)]
19pub struct ComplexPolar<FT> {
20    pub abs: FT,
21    pub arg: FT,
22}
23
24impl<FT> ComplexPolar<FT> {
25    /// Creates a complex number.
26    pub const fn new(abs: FT, arg: FT) -> Self {
27        Self { abs, arg }
28    }
29}
30
31impl<FT: Number> ComplexPolar<FT> {
32    pub const ZERO: Self = Self::new(FT::ZERO, FT::ZERO);
33    pub const ONE: Self = Self::new(FT::ONE, FT::ZERO);
34
35    /// Computes the conjugate.
36    pub fn conjugate(self) -> Self {
37        Self::new(self.abs, -self.arg)
38    }
39
40    /// Computes the real component.
41    pub fn re(self) -> FT {
42        self.abs * self.arg.cos()
43    }
44
45    /// Computes the imaginary component.
46    pub fn im(self) -> FT {
47        self.abs * self.arg.sin()
48    }
49
50    /// Computes the squared absolute value.
51    pub fn abs_sq(self) -> FT {
52        self.abs * self.abs
53    }
54
55    /// Computes the reciprocal.
56    pub fn recip(self) -> Self {
57        Self::new(self.abs.recip(), -self.arg)
58    }
59
60    /// Computes the principal square root.
61    pub fn sqrt(self) -> Self {
62        let two = FT::ONE + FT::ONE;
63        Self::new(self.abs.sqrt(), self.arg / two)
64    }
65
66    /// Convert to rectangular form.
67    pub fn to_rectangular(self) -> Rectangular<FT> {
68        let (sin, cos) = self.arg.sin_cos();
69        Rectangular::new(cos, sin) * self.abs
70    }
71
72    /// Computes `e^self` where `e` is the base of the natural logarithm.
73    pub fn exp(self) -> Self {
74        self.to_rectangular().exp()
75    }
76
77    /// Computes `2^self`.
78    pub fn exp2(self) -> Self {
79        self.to_rectangular().exp2()
80    }
81
82    /// Computes `e^self - 1`.
83    ///
84    /// More numerically stable than `self.exp().to_rectangular() - 1` when `self ≈ 0`.
85    pub fn expm1(self) -> Rectangular<FT> {
86        self.to_rectangular().expm1()
87    }
88
89    /// Computes the principal natural logarithm.
90    pub fn ln(self) -> Rectangular<FT> {
91        Rectangular::new(self.abs.ln(), self.arg)
92    }
93
94    /// Computes the principal natural logarithm of `1 + self`.
95    ///
96    /// More numerically stable than `(self + 1).ln()` when `self ≈ 0`.
97    pub fn ln_1p(self) -> Rectangular<FT> {
98        self.to_rectangular().ln_1p()
99    }
100
101    /// Computes the principal logarithm in base 2.
102    pub fn log2(self) -> Rectangular<FT> {
103        self.ln() / FT::LN_2()
104    }
105
106    /// Computes the principal logarithm in base 10.
107    pub fn log10(self) -> Rectangular<FT> {
108        self.ln() / FT::LN_10()
109    }
110
111    /// Computes the k-th branch of the natural logarithm.
112    ///
113    /// The principal value is `k = 0`. Each increment of `k` adds `2πi`.
114    pub fn ln_branch(self, k: i32) -> Rectangular<FT> {
115        Rectangular::new(self.abs.ln(), self.arg + FT::TAU() * FT::from_i32(k))
116    }
117
118    /// Computes the k-th branch of the natural logarithm of `1 + self`.
119    ///
120    /// The principal value is `k = 0`. Each increment of `k` adds `2πi`.
121    pub fn ln_1p_branch(self, k: i32) -> Rectangular<FT> {
122        self.to_rectangular().ln_1p_branch(k)
123    }
124
125    /// Computes the k-th branch of the base-2 logarithm.
126    pub fn log2_branch(self, k: i32) -> Rectangular<FT> {
127        self.ln_branch(k) / FT::LN_2()
128    }
129
130    /// Computes the k-th branch of the base-10 logarithm.
131    pub fn log10_branch(self, k: i32) -> Rectangular<FT> {
132        self.ln_branch(k) / FT::LN_10()
133    }
134
135    /// Computes the k-th square root.
136    ///
137    /// The principal value is `k = 0`. Only `k = 0` and `k = 1` give distinct values.
138    pub fn sqrt_branch(self, k: i32) -> Self {
139        let two = FT::ONE + FT::ONE;
140        Self::new(
141            self.abs.sqrt(),
142            (self.arg + FT::TAU() * FT::from_i32(k)) / two,
143        )
144    }
145
146    /// Computes the k-th value of the n-th root.
147    ///
148    /// The `n` distinct values correspond to `k = 0..n-1`.
149    pub fn nth_root(self, n: i32, k: i32) -> Self {
150        Self::new(
151            self.abs.powf(FT::from_i32(n).recip()),
152            (self.arg + FT::TAU() * FT::from_i32(k)) / FT::from_i32(n),
153        )
154    }
155
156    /// Raises `self` to the rational power `p/q`, selecting the k-th branch.
157    ///
158    /// There are `q` distinct values corresponding to `k = 0..q-1`, provided `p/q` is in lowest
159    /// terms. If `p/q` is not reduced, first reduce it to find the true number of distinct values.
160    pub fn pow_rational(self, p: i32, q: i32, k: i32) -> Self {
161        self.nth_root(q, k).powi(p)
162    }
163
164    /// Raises `self` to a floating point power.
165    pub fn powf(self, x: FT) -> Self {
166        if x < FT::ZERO && self.abs == FT::ZERO {
167            return Self::ZERO;
168        }
169        Self::new(self.abs.powf(x), self.arg * x)
170    }
171
172    /// Raises `self` to an integer power.
173    pub fn powi(self, n: i32) -> Self {
174        if n < 0 && self.abs == FT::ZERO {
175            return Self::ZERO;
176        }
177        Self::new(self.abs.powi(n), self.arg * FT::from_i32(n))
178    }
179
180    /// Normalizes the absolute value and the argument into the range `[0, ∞)` and `(-π, +π]` respectively.
181    pub fn normalize(mut self) -> Self {
182        self.arg = self.arg.rem_euclid(&FT::TAU());
183        if self.abs < FT::ZERO {
184            self.abs = -self.abs;
185            if self.arg <= FT::ZERO {
186                self.arg += FT::PI();
187            } else {
188                self.arg -= FT::PI();
189            }
190        } else if self.arg > FT::PI() {
191            self.arg -= FT::TAU();
192        } else if self.arg <= -FT::PI() {
193            self.arg += FT::TAU();
194        }
195        self
196    }
197}
198
199impl<FT: Number> Mul for ComplexPolar<FT> {
200    type Output = Self;
201    fn mul(mut self, other: Self) -> Self {
202        self *= other;
203        self
204    }
205}
206
207impl<FT: Number> Mul<FT> for ComplexPolar<FT> {
208    type Output = Self;
209    fn mul(mut self, re: FT) -> Self::Output {
210        self *= re;
211        self
212    }
213}
214
215impl<FT: Number> MulAssign for ComplexPolar<FT> {
216    fn mul_assign(&mut self, other: Self) {
217        self.abs *= other.abs;
218        self.arg += other.arg;
219    }
220}
221
222impl<FT: Number> MulAssign<FT> for ComplexPolar<FT> {
223    fn mul_assign(&mut self, re: FT) {
224        self.abs *= re;
225    }
226}
227
228impl<FT: Number> Div for ComplexPolar<FT> {
229    type Output = Self;
230    fn div(mut self, other: Self) -> Self {
231        self /= other;
232        self
233    }
234}
235
236impl<FT: Number> Div<FT> for ComplexPolar<FT> {
237    type Output = Self;
238    fn div(mut self, re: FT) -> Self {
239        self /= re;
240        self
241    }
242}
243
244impl<FT: Number> DivAssign for ComplexPolar<FT> {
245    fn div_assign(&mut self, other: Self) {
246        *self *= other.recip();
247    }
248}
249
250impl<FT: Number> DivAssign<FT> for ComplexPolar<FT> {
251    fn div_assign(&mut self, re: FT) {
252        self.abs /= re;
253    }
254}
255
256impl<FT: Number> Neg for ComplexPolar<FT> {
257    type Output = Self;
258    fn neg(mut self) -> Self {
259        self.abs = -self.abs;
260        self
261    }
262}
263
264impl<FT: Number + fmt::Display> fmt::Display for ComplexPolar<FT> {
265    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
266        fn fmt_x<FT: fmt::Display>(f: &mut fmt::Formatter, x: FT) -> fmt::Result {
267            if let Some(p) = f.precision() {
268                write!(f, "{x:.*}", p)
269            } else {
270                write!(f, "{x}")
271            }
272        }
273        let pi_radians = self.arg / FT::PI();
274        fmt_x(f, self.abs)?;
275        if pi_radians == FT::ZERO || self.abs == FT::ZERO {
276            Ok(())
277        } else if pi_radians == FT::ONE {
278            write!(f, "e^iπ")
279        } else {
280            write!(f, "e^")?;
281            fmt_x(f, pi_radians)?;
282            write!(f, "iπ")
283        }
284    }
285}
286
287impl<FT: Number> From<FT> for ComplexPolar<FT> {
288    fn from(value: FT) -> Self {
289        Self::new(value, FT::ZERO)
290    }
291}
292
293#[cfg(feature = "approx")]
294use approx::{AbsDiffEq, RelativeEq, UlpsEq};
295
296#[cfg(feature = "approx")]
297impl<FT: AbsDiffEq + Copy> AbsDiffEq for ComplexPolar<FT>
298where
299    <FT as AbsDiffEq>::Epsilon: Copy,
300{
301    type Epsilon = <FT as AbsDiffEq>::Epsilon;
302    fn default_epsilon() -> Self::Epsilon {
303        FT::default_epsilon()
304    }
305    fn abs_diff_eq(&self, other: &Self, epsilon: Self::Epsilon) -> bool {
306        FT::abs_diff_eq(&self.abs, &other.abs, epsilon)
307            && FT::abs_diff_eq(&self.arg, &other.arg, epsilon)
308    }
309}
310
311#[cfg(feature = "approx")]
312impl<FT: RelativeEq + Copy> RelativeEq for ComplexPolar<FT>
313where
314    <FT as AbsDiffEq>::Epsilon: Copy,
315{
316    fn default_max_relative() -> Self::Epsilon {
317        FT::default_max_relative()
318    }
319    fn relative_eq(
320        &self,
321        other: &Self,
322        epsilon: Self::Epsilon,
323        max_relative: Self::Epsilon,
324    ) -> bool {
325        FT::relative_eq(&self.abs, &other.abs, epsilon, max_relative)
326            && FT::relative_eq(&self.arg, &other.arg, epsilon, max_relative)
327    }
328}
329
330#[cfg(feature = "approx")]
331impl<FT: UlpsEq + Copy> UlpsEq for ComplexPolar<FT>
332where
333    <FT as AbsDiffEq>::Epsilon: Copy,
334{
335    fn default_max_ulps() -> u32 {
336        FT::default_max_ulps()
337    }
338    fn ulps_eq(&self, other: &Self, epsilon: Self::Epsilon, max_ulps: u32) -> bool {
339        FT::ulps_eq(&self.abs, &other.abs, epsilon, max_ulps)
340            && FT::ulps_eq(&self.arg, &other.arg, epsilon, max_ulps)
341    }
342}