Skip to main content

oxilean_std/complex/
complex_new_group.rs

1//! # Complex - new_group Methods
2//!
3//! This module contains method implementations for `Complex`.
4//!
5//! 🤖 Generated with [SplitRS](https://github.com/cool-japan/splitrs)
6
7use super::complex_type::Complex;
8
9impl Complex {
10    /// Create a new complex number.
11    pub fn new(re: f64, im: f64) -> Self {
12        Self { re, im }
13    }
14    /// Zero.
15    pub fn zero() -> Self {
16        Self::new(0.0, 0.0)
17    }
18    /// One.
19    pub fn one() -> Self {
20        Self::new(1.0, 0.0)
21    }
22    /// Imaginary unit i.
23    pub fn i() -> Self {
24        Self::new(0.0, 1.0)
25    }
26    /// Complex conjugate: a + bi → a - bi.
27    pub fn conj(self) -> Self {
28        Self::new(self.re, -self.im)
29    }
30    /// Addition.
31    pub fn add(self, other: Self) -> Self {
32        Self::new(self.re + other.re, self.im + other.im)
33    }
34    /// Subtraction.
35    pub fn sub(self, other: Self) -> Self {
36        Self::new(self.re - other.re, self.im - other.im)
37    }
38    /// Multiplication: (a+bi)(c+di) = (ac-bd) + (ad+bc)i.
39    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    /// Scalar multiplication.
46    pub fn scale(self, s: f64) -> Self {
47        Self::new(self.re * s, self.im * s)
48    }
49    /// Negation.
50    pub fn neg(self) -> Self {
51        Self::new(-self.re, -self.im)
52    }
53    /// Complex exponential: exp(a+bi) = e^a * (cos b + i sin b).
54    pub fn exp(self) -> Self {
55        let ea = self.re.exp();
56        Self::new(ea * self.im.cos(), ea * self.im.sin())
57    }
58    /// Principal complex logarithm: log(z) = ln|z| + i·arg(z).
59    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    /// Principal square root.
66    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    /// Complex sine: sin(z) = (e^(iz) - e^(-iz)) / (2i).
75    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    /// Polar form: (r, θ) → r·(cos θ + i·sin θ).
82    pub fn from_polar(r: f64, theta: f64) -> Self {
83        Self::new(r * theta.cos(), r * theta.sin())
84    }
85}