Skip to main content

fontoxide_misc/
complex.rs

1//! Python's `complex`, as fontTools' curve math uses it.
2//!
3//! The operations follow CPython 3.13 (`Objects/complexobject.c`) so that the
4//! results are bit for bit the same, signed zeros included: a real operand is
5//! first converted to a complex number with a zero imaginary part, so
6//! `2.0 * z` is a full complex product (`_Py_c_prod`), and `z / 2.0` goes
7//! through `_Py_c_quot`.
8
9use std::ops::{Add, AddAssign, Mul, Neg, Sub};
10
11/// A complex number (`complex`).
12#[derive(Debug, Clone, Copy, PartialEq, Default)]
13pub struct Complex {
14	/// `real`.
15	pub re: f64,
16	/// `imag`.
17	pub im: f64,
18}
19
20/// `1j`.
21pub const J: Complex = Complex { re: 0.0, im: 1.0 };
22
23impl Complex {
24	/// `complex(re, im)`.
25	pub const fn new(re: f64, im: f64) -> Self {
26		Complex { re, im }
27	}
28
29	/// `complex(re)`, or a real number as an operand of a complex operation.
30	pub const fn real(re: f64) -> Self {
31		Complex { re, im: 0.0 }
32	}
33
34	/// `complex(*pt)`.
35	pub const fn from_point((x, y): (f64, f64)) -> Self {
36		Complex { re: x, im: y }
37	}
38
39	/// `(z.real, z.imag)`.
40	pub const fn to_point(self) -> (f64, f64) {
41		(self.re, self.im)
42	}
43
44	/// `abs(z)`: `hypot(real, imag)`.
45	pub fn abs(self) -> f64 {
46		self.re.hypot(self.im)
47	}
48
49	/// `z.conjugate()`.
50	pub const fn conj(self) -> Self {
51		Complex {
52			re: self.re,
53			im: -self.im,
54		}
55	}
56
57	/// `z * x` or `x * z` for a real `x` (`_Py_c_prod` with `complex(x)`).
58	pub fn scale(self, x: f64) -> Self {
59		self * Complex::real(x)
60	}
61
62	/// `z / x` for a real `x` (`_Py_c_quot` with `complex(x)`). `None` for
63	/// `ZeroDivisionError`.
64	pub fn div_real(self, x: f64) -> Option<Self> {
65		self.quot(Complex::real(x))
66	}
67
68	/// `a / b` (`_Py_c_quot`). `None` for `ZeroDivisionError`.
69	pub fn quot(self, b: Complex) -> Option<Self> {
70		let a = self;
71		let abs_breal = if b.re < 0.0 { -b.re } else { b.re };
72		let abs_bimag = if b.im < 0.0 { -b.im } else { b.im };
73		if abs_breal >= abs_bimag {
74			if abs_breal == 0.0 {
75				return None;
76			}
77			let ratio = b.im / b.re;
78			let denom = b.re + b.im * ratio;
79			Some(Complex {
80				re: (a.re + a.im * ratio) / denom,
81				im: (a.im - a.re * ratio) / denom,
82			})
83		} else if abs_bimag >= abs_breal {
84			let ratio = b.re / b.im;
85			let denom = b.re * ratio + b.im;
86			Some(Complex {
87				re: (a.re * ratio + a.im) / denom,
88				im: (a.im * ratio - a.re) / denom,
89			})
90		} else {
91			// At least one of b.real or b.imag is a NaN.
92			Some(Complex {
93				re: f64::NAN,
94				im: f64::NAN,
95			})
96		}
97	}
98
99	/// Whether either part is a NaN.
100	pub fn is_nan(self) -> bool {
101		self.re.is_nan() || self.im.is_nan()
102	}
103
104	/// `repr(z)`: `(1+2j)`, or `2j` if the real part is a positive zero. The
105	/// parts are formatted with `repr`, without a `.0` for integral values.
106	pub fn repr(self) -> String {
107		fn r(x: f64) -> String {
108			let s = crate::py::float_repr(x);
109			s.strip_suffix(".0").map(str::to_owned).unwrap_or(s)
110		}
111		if self.re == 0.0 && self.re.is_sign_positive() {
112			return format!("{}j", r(self.im));
113		}
114		let im = r(self.im);
115		let sign = if im.starts_with('-') { "" } else { "+" };
116		format!("({}{sign}{im}j)", r(self.re))
117	}
118}
119
120impl Add for Complex {
121	type Output = Complex;
122
123	fn add(self, b: Complex) -> Complex {
124		Complex {
125			re: self.re + b.re,
126			im: self.im + b.im,
127		}
128	}
129}
130
131impl AddAssign for Complex {
132	fn add_assign(&mut self, b: Complex) {
133		*self = *self + b;
134	}
135}
136
137impl Sub for Complex {
138	type Output = Complex;
139
140	fn sub(self, b: Complex) -> Complex {
141		Complex {
142			re: self.re - b.re,
143			im: self.im - b.im,
144		}
145	}
146}
147
148impl Neg for Complex {
149	type Output = Complex;
150
151	fn neg(self) -> Complex {
152		Complex {
153			re: -self.re,
154			im: -self.im,
155		}
156	}
157}
158
159/// `_Py_c_prod`.
160impl Mul for Complex {
161	type Output = Complex;
162
163	fn mul(self, b: Complex) -> Complex {
164		Complex {
165			re: self.re * b.re - self.im * b.im,
166			im: self.re * b.im + self.im * b.re,
167		}
168	}
169}
170
171/// `z * x` for a real `x`, as a full complex product.
172impl Mul<f64> for Complex {
173	type Output = Complex;
174
175	fn mul(self, x: f64) -> Complex {
176		self.scale(x)
177	}
178}
179
180/// `x * z` for a real `x`, as a full complex product.
181impl Mul<Complex> for f64 {
182	type Output = Complex;
183
184	fn mul(self, z: Complex) -> Complex {
185		Complex::real(self) * z
186	}
187}
188
189#[cfg(test)]
190mod tests {
191	use super::*;
192
193	#[test]
194	fn signed_zeros_follow_cpython() {
195		// `-0.0 * complex(1, -2)` is `0j` in Python 3.13: the real operand is
196		// promoted, and `-0.0*1 - 0*(-2)` is `+0.0`.
197		let z = -0.0 * Complex::new(1.0, -2.0);
198		assert!(z.re == 0.0 && z.re.is_sign_positive());
199		assert!(z.im == 0.0 && z.im.is_sign_positive());
200		assert_eq!(Complex::new(3.0, 4.0).abs(), 5.0);
201		assert_eq!(Complex::new(1.0, 2.0).div_real(0.0), None);
202		assert_eq!(
203			Complex::new(1.0, 2.0).div_real(4.0),
204			Some(Complex::new(0.25, 0.5))
205		);
206		assert_eq!(Complex::new(2.0, 3.0) * J, Complex::new(-3.0, 2.0));
207	}
208}