Skip to main content

lib_jsl_dsp/discrete/sources/
cordic.rs

1//! Fixed-point CORDIC sine/cosine, in 32-bit and 64-bit word sizes.
2//!
3//! The COordinate Rotation DIgital Computer computes sine and cosine with only shifts and adds: a
4//! vector is rotated toward the target angle by a fixed sequence of micro-rotations of angle
5//! `atan(2^-i)`, each chosen clockwise or counter-clockwise. This implementation is entirely
6//! integer arithmetic, as it would be in hardware, and the single algorithm is instantiated for two
7//! word sizes:
8//!
9//! | type | angle | results | max iterations | accuracy |
10//! |------|-------|---------|----------------|----------|
11//! | [`Cordic32`] (alias [`Cordic`]) | `u32` binary angle | `i32`, Q1.30 | 30 | about 1e-8 |
12//! | [`Cordic64`] | `u64` binary angle | `i64`, Q1.62 | 62 | about 4e-16 at 52 iterations |
13//!
14//! A *binary angle* has `2^N` units per turn, so it wraps naturally and its top two bits select the
15//! quadrant. Results are signed (sine and cosine go negative) with `1.0` represented as
16//! `1 << FRACTIONAL_BITS`. The micro-rotation angles and the cumulative gain compensation are
17//! precomputed integer tables, and the shifts use round-to-nearest to keep the bias down.
18//!
19//! Widening only the data would not help: the angle's resolution limits the accuracy, so both words
20//! grow together. `Cordic32` is the hardware-style choice (1e-8 is about -160 dB, beyond what a
21//! 24-bit converter chain can use); `Cordic64` matches the 64-bit phase of the NCO and reaches
22//! double-precision accuracy, at the cost of about 1.7 times as many iterations.
23//!
24//! See the book entry [Signal sources: oscillators, CORDIC and waveforms](https://jwkunz.github.io/lib_jsl/book/comms/sources.html#cordic).
25
26use lib_jsl_core::ErrorsJSL;
27use std::f64::consts::TAU;
28use std::sync::OnceLock;
29
30/// `atan(2^-i)` as a binary angle (`2^32` per turn).
31const ATAN_BAM_32: [u32; 30] = [
32    0x20000000, 0x12E4051E, 0x09FB385B, 0x051111D4, 0x028B0D43,
33    0x0145D7E1, 0x00A2F61E, 0x00517C55, 0x0028BE53, 0x00145F2F,
34    0x000A2F98, 0x000517CC, 0x00028BE6, 0x000145F3, 0x0000A2FA,
35    0x0000517D, 0x000028BE, 0x0000145F, 0x00000A30, 0x00000518,
36    0x0000028C, 0x00000146, 0x000000A3, 0x00000051, 0x00000029,
37    0x00000014, 0x0000000A, 0x00000005, 0x00000003, 0x00000001,
38];
39
40/// `1 / K_n` in Q1.30, where `K_n = Π_{i<n} sqrt(1 + 2^-2i)` is the gain after `n` iterations.
41const INV_GAIN_Q30: [i32; 31] = [
42    1073741824, 759250125, 679093957, 658817909, 653730436,
43    652457347, 652138997, 652059405, 652039507, 652034532,
44    652033289, 652032978, 652032900, 652032881, 652032876,
45    652032874, 652032874, 652032874, 652032874, 652032874,
46    652032874, 652032874, 652032874, 652032874, 652032874,
47    652032874, 652032874, 652032874, 652032874, 652032874,
48    652032874,
49];
50
51
52const ATAN_BAM_64: [u64; 62] = [
53    0x2000000000000000, 0x12E4051D9DF30866, 0x09FB385B5EE39E8E,
54    0x051111D41DDD9A1B, 0x028B0D430E589AED, 0x0145D7E159046278,
55    0x00A2F61E5C28262A, 0x00517C5511D442AF, 0x0028BE5346D0C337,
56    0x00145F2EBB30AB38, 0x000A2F980091BA7B, 0x000517CC14A80CB7,
57    0x00028BE60CDFEC62, 0x000145F306C172F2, 0x0000A2F9836AE911,
58    0x0000517CC1B6BA7C, 0x000028BE60DB85FC, 0x0000145F306DC816,
59    0x00000A2F9836E4AE, 0x00000517CC1B726B, 0x0000028BE60DB938,
60    0x00000145F306DC9C, 0x000000A2F9836E4E, 0x000000517CC1B727,
61    0x00000028BE60DB94, 0x000000145F306DCA, 0x0000000A2F9836E5,
62    0x0000000517CC1B72, 0x000000028BE60DB9, 0x0000000145F306DD,
63    0x00000000A2F9836E, 0x00000000517CC1B7, 0x0000000028BE60DC,
64    0x00000000145F306E, 0x000000000A2F9837, 0x000000000517CC1B,
65    0x00000000028BE60E, 0x000000000145F307, 0x0000000000A2F983,
66    0x0000000000517CC2, 0x000000000028BE61, 0x0000000000145F30,
67    0x00000000000A2F98, 0x00000000000517CC, 0x0000000000028BE6,
68    0x00000000000145F3, 0x000000000000A2FA, 0x000000000000517D,
69    0x00000000000028BE, 0x000000000000145F, 0x0000000000000A30,
70    0x0000000000000518, 0x000000000000028C, 0x0000000000000146,
71    0x00000000000000A3, 0x0000000000000051, 0x0000000000000029,
72    0x0000000000000014, 0x000000000000000A, 0x0000000000000005,
73    0x0000000000000003, 0x0000000000000001,
74];
75
76const INV_GAIN_Q62: [i64; 63] = [
77    4611686018427387904, 3260954456333195553, 2916686334356757942,
78    2829601372552588592, 2807750841902562267, 2802282967498353433,
79    2800915666627739259, 2800573820569637254, 2800488357751430639,
80    2800466991965380887, 2800461650513774536, 2800460315150554575,
81    2800459981309729686, 2800459897849522220, 2800459876984470276,
82    2800459871768207285, 2800459870464141537, 2800459870138125100,
83    2800459870056620990, 2800459870036244963, 2800459870031150956,
84    2800459870029877455, 2800459870029559079, 2800459870029479485,
85    2800459870029459587, 2800459870029454612, 2800459870029453369,
86    2800459870029453058, 2800459870029452980, 2800459870029452960,
87    2800459870029452956, 2800459870029452954, 2800459870029452954,
88    2800459870029452954, 2800459870029452954, 2800459870029452954,
89    2800459870029452954, 2800459870029452954, 2800459870029452954,
90    2800459870029452954, 2800459870029452954, 2800459870029452954,
91    2800459870029452954, 2800459870029452954, 2800459870029452954,
92    2800459870029452954, 2800459870029452954, 2800459870029452954,
93    2800459870029452954, 2800459870029452954, 2800459870029452954,
94    2800459870029452954, 2800459870029452954, 2800459870029452954,
95    2800459870029452954, 2800459870029452954, 2800459870029452954,
96    2800459870029452954, 2800459870029452954, 2800459870029452954,
97    2800459870029452954, 2800459870029452954, 2800459870029452954,
98];
99
100/// Defines a CORDIC rotator type for one angle/word size. The algorithm is written once here.
101macro_rules! define_cordic {
102    (
103        $(#[$meta:meta])*
104        $name:ident,
105        angle: $A:ty,
106        word: $W:ty,
107        angle_bits: $ABITS:expr,
108        frac_bits: $FRAC:expr,
109        max_iterations: $MAX:expr,
110        default_iterations: $DEF:expr,
111        atan: $ATAN:ident,
112        inv_gain: $INV:ident
113    ) => {
114        $(#[$meta])*
115        #[derive(Clone, Copy, Debug)]
116        pub struct $name {
117            iterations: u32,
118        }
119
120        impl $name {
121            /// Number of fractional bits in the signed results.
122            pub const FRACTIONAL_BITS: u32 = $FRAC;
123            /// The fixed-point representation of 1.0.
124            pub const ONE: $W = 1 << $FRAC;
125            /// The maximum number of micro-rotations.
126            pub const MAX_ITERATIONS: u32 = $MAX;
127            /// A good default iteration count (about the accuracy floor of the word size).
128            pub const DEFAULT_ITERATIONS: u32 = $DEF;
129
130            /// Creates a rotator with `iterations` micro-rotations (1 to [`Self::MAX_ITERATIONS`]).
131            pub fn new(iterations: u32) -> Result<$name, ErrorsJSL> {
132                if !(1..=$MAX).contains(&iterations) {
133                    return Err(ErrorsJSL::InvalidInputRange("CORDIC iteration count is out of range."));
134                }
135                Ok($name { iterations })
136            }
137
138            pub fn iterations(&self) -> u32 {
139                self.iterations
140            }
141
142            /// The gain `K = Π sqrt(1 + 2^-2i)` that the micro-rotations add (about 1.6468), which
143            /// the rotator compensates for by starting from `1/K`.
144            pub fn gain(&self) -> f64 {
145                (0..self.iterations).map(|i| (1.0 + 0.25f64.powi(i as i32)).sqrt()).product()
146            }
147
148            /// Rounding arithmetic right shift.
149            fn shr_round(v: $W, shift: u32) -> $W {
150                if shift == 0 { v } else { (v + (1 << (shift - 1))) >> shift }
151            }
152
153            /// Returns `(sin, cos)` of a binary angle as signed fixed-point values with
154            /// [`Self::FRACTIONAL_BITS`] fractional bits, using integer arithmetic only.
155            pub fn sin_cos_fixed(&self, angle: $A) -> ($W, $W) {
156                let inv_gain = $INV[self.iterations as usize];
157                // The top two bits give the quadrant: start from the gain-compensated unit vector
158                // already rotated by that many quarter turns, then rotate by the remaining angle
159                // in [0, pi/2).
160                // ANCHOR: cordic
161                let (mut x, mut y): ($W, $W) = match angle >> ($ABITS - 2) {
162                    0 => (inv_gain, 0),
163                    1 => (0, inv_gain),
164                    2 => (-inv_gain, 0),
165                    _ => (0, -inv_gain),
166                };
167                let mut z = (angle & (<$A>::MAX >> 2)) as $W;
168                for i in 0..self.iterations {
169                    let (dx, dy) = (Self::shr_round(y, i), Self::shr_round(x, i));
170                    let theta = $ATAN[i as usize] as $W;
171                    if z >= 0 {
172                        x -= dx;
173                        y += dy;
174                        z -= theta;
175                    } else {
176                        x += dx;
177                        y -= dy;
178                        z += theta;
179                    }
180                }
181                (y, x)
182            }
183                // ANCHOR_END: cordic
184
185            /// Floating-point convenience: `(sin, cos)` of an angle in radians (any real value).
186            /// The angle is first quantized to a binary angle.
187            pub fn sin_cos(&self, radians: f64) -> (f64, f64) {
188                let (s, c) = self.sin_cos_fixed(Self::angle_from_radians(radians));
189                (s as f64 / Self::ONE as f64, c as f64 / Self::ONE as f64)
190            }
191
192            /// Converts an angle in turns to a binary angle (modulo one turn).
193            pub fn angle_from_turns(turns: f64) -> $A {
194                ((turns.rem_euclid(1.0) * 2f64.powi($ABITS)).round() as u128) as $A // a full turn wraps to 0
195            }
196
197            /// Converts an angle in radians to a binary angle (modulo one turn).
198            pub fn angle_from_radians(radians: f64) -> $A {
199                Self::angle_from_turns(radians / TAU)
200            }
201
202            /// Converts a binary angle to radians in `[0, 2*pi)`.
203            pub fn angle_to_radians(angle: $A) -> f64 {
204                angle as f64 / 2f64.powi($ABITS) * TAU
205            }
206        }
207    };
208}
209
210define_cordic! {
211    /// A 32-bit CORDIC rotator: `u32` binary angles (`2^32` per turn) and `i32` Q1.30 results.
212    /// Accurate to about 1e-8 (a dozen least-significant bits) at 30 iterations.
213    Cordic32,
214    angle: u32,
215    word: i32,
216    angle_bits: 32,
217    frac_bits: 30,
218    max_iterations: 30,
219    default_iterations: 30,
220    atan: ATAN_BAM_32,
221    inv_gain: INV_GAIN_Q30
222}
223
224define_cordic! {
225    /// A 64-bit CORDIC rotator: `u64` binary angles (`2^64` per turn, the same width as the NCO
226    /// phase) and `i64` Q1.62 results. Reaches double-precision accuracy (about 4e-16) at 52
227    /// iterations and about 3e-18 at the maximum of 62.
228    Cordic64,
229    angle: u64,
230    word: i64,
231    angle_bits: 64,
232    frac_bits: 62,
233    max_iterations: 62,
234    default_iterations: 52,
235    atan: ATAN_BAM_64,
236    inv_gain: INV_GAIN_Q62
237}
238
239/// The 32-bit rotator, kept under its original name.
240pub type Cordic = Cordic32;
241
242/// Number of fractional bits in [`Cordic32`] results.
243pub const FRACTIONAL_BITS: u32 = Cordic32::FRACTIONAL_BITS;
244/// The [`Cordic32`] fixed-point representation of 1.0.
245pub const ONE: i32 = Cordic32::ONE;
246/// The maximum number of [`Cordic32`] micro-rotations.
247pub const MAX_ITERATIONS: u32 = Cordic32::MAX_ITERATIONS;
248
249/// Converts an angle in radians to a `u32` binary angle (modulo one turn).
250pub fn angle_from_radians(radians: f64) -> u32 {
251    Cordic32::angle_from_radians(radians)
252}
253
254/// Converts an angle in turns to a `u32` binary angle (modulo one turn).
255pub fn angle_from_turns(turns: f64) -> u32 {
256    Cordic32::angle_from_turns(turns)
257}
258
259/// Converts a `u32` binary angle to radians in `[0, 2*pi)`.
260pub fn angle_to_radians(angle: u32) -> f64 {
261    Cordic32::angle_to_radians(angle)
262}
263
264/// Returns `(sin(angle), cos(angle))` for an angle in radians, using the 32-bit integer CORDIC with
265/// [`Cordic32::DEFAULT_ITERATIONS`] (accurate to about 1e-8). Use [`Cordic64`] for full
266/// double-precision accuracy.
267pub fn cordic_sin_cos(angle: f64) -> (f64, f64) {
268    static DEFAULT: OnceLock<Cordic32> = OnceLock::new();
269    DEFAULT.get_or_init(|| Cordic32::new(Cordic32::DEFAULT_ITERATIONS).expect("valid iteration count")).sin_cos(angle)
270}
271
272#[cfg(test)]
273mod tests {
274    use super::*;
275
276    const LSB: f64 = 1.0 / ONE as f64;
277
278    /// Worst error against libm over a dense sweep of binary angles.
279    fn max_error(c: &Cordic32, step: u32) -> f64 {
280        let mut worst = 0.0f64;
281        let mut a = 0u32;
282        loop {
283            let (s, co) = c.sin_cos_fixed(a);
284            let r = angle_to_radians(a);
285            worst = worst.max((s as f64 * LSB - r.sin()).abs()).max((co as f64 * LSB - r.cos()).abs());
286            match a.checked_add(step) {
287                Some(n) => a = n,
288                None => break,
289            }
290        }
291        worst
292    }
293
294    #[allow(clippy::needless_range_loop)]
295    #[test]
296    fn tables_match_their_definitions() {
297        for (i, &t) in ATAN_BAM_32.iter().enumerate() {
298            let want = (0.5f64.powi(i as i32)).atan() / TAU * 4_294_967_296.0;
299            assert!((t as f64 - want).abs() <= 0.5 + 1e-6, "atan table entry {i}");
300        }
301        for n in 1..=30usize {
302            let gain: f64 = (0..n).map(|i| (1.0 + 0.25f64.powi(i as i32)).sqrt()).product();
303            assert!((INV_GAIN_Q30[n] as f64 - ONE as f64 / gain).abs() <= 0.5 + 1e-6, "gain table entry {n}");
304        }
305    }
306
307    #[test]
308    fn full_precision_accuracy_over_the_whole_circle() {
309        let c = Cordic::new(30).unwrap();
310        let err = max_error(&c, 104_729); // ~41k angles, covering all four quadrants
311        assert!(err < 16.0 * LSB, "max error {err} ({} LSB)", err / LSB);
312    }
313
314    #[test]
315    fn quadrant_boundaries_and_symmetry() {
316        let c = Cordic::new(30).unwrap();
317        let near = |got: i32, want: i32| (got - want).abs() <= 6;
318        let (s, co) = c.sin_cos_fixed(0);
319        assert!(near(s, 0) && near(co, ONE));
320        let (s, co) = c.sin_cos_fixed(1 << 30); // 90 degrees
321        assert!(near(s, ONE) && near(co, 0));
322        let (s, co) = c.sin_cos_fixed(1 << 31); // 180 degrees
323        assert!(near(s, 0) && near(co, -ONE));
324        let (s, co) = c.sin_cos_fixed(3 << 30); // 270 degrees
325        assert!(near(s, -ONE) && near(co, 0));
326        // 45 degrees
327        let (s, co) = c.sin_cos_fixed(1 << 29);
328        let h = (ONE as f64 * std::f64::consts::FRAC_1_SQRT_2) as i32;
329        assert!(near(s, h) && near(co, h));
330        // Adding a quarter turn rotates (sin, cos) to (cos, -sin).
331        for a in [123_456u32, 987_654_321, 2_000_000_000, 4_000_000_000] {
332            let (s0, c0) = c.sin_cos_fixed(a);
333            let (s1, c1) = c.sin_cos_fixed(a.wrapping_add(1 << 30));
334            assert!((s1 - c0).abs() <= 12 && (c1 + s0).abs() <= 12, "angle {a}");
335        }
336    }
337
338    #[test]
339    fn error_shrinks_with_iterations_down_to_the_fixed_point_floor() {
340        let errs: Vec<f64> = [4u32, 8, 12, 16, 20, 24, 30].iter().map(|&n| max_error(&Cordic::new(n).unwrap(), 1_000_003)).collect();
341        for w in errs[..5].windows(2) {
342            assert!(w[1] < w[0] * 0.2, "{errs:?}");
343        }
344        assert!(errs[0] < 0.2 && errs[3] < 1e-4 && errs[5] < 2e-6 && errs[6] < 2e-8, "{errs:?}");
345    }
346
347    #[test]
348    fn unit_magnitude_and_gain() {
349        let c = Cordic::new(30).unwrap();
350        assert!((c.gain() - 1.646760258121066).abs() < 1e-12);
351        assert_eq!(c.iterations(), 30);
352        for k in 0..2000u32 {
353            let (s, co) = c.sin_cos_fixed(k.wrapping_mul(2_147_483_659));
354            let mag = ((s as f64).powi(2) + (co as f64).powi(2)).sqrt() * LSB;
355            assert!((mag - 1.0).abs() < 1e-8, "angle index {k}: {mag}");
356        }
357    }
358
359    #[test]
360    fn float_wrappers_and_angle_conversion() {
361        for k in -300..=300 {
362            let a = k as f64 * 0.0271;
363            let (s, c) = cordic_sin_cos(a);
364            assert!((s - a.sin()).abs() < 1e-8 && (c - a.cos()).abs() < 1e-8, "angle {a}");
365        }
366        let (s, _) = cordic_sin_cos(1000.0 * TAU + 0.3);
367        assert!((s - 0.3f64.sin()).abs() < 1e-8);
368        assert_eq!(angle_from_turns(0.25), 1 << 30);
369        assert_eq!(angle_from_turns(-0.25), 3 << 30);
370        assert_eq!(angle_from_turns(1.0), 0);
371        assert_eq!(angle_from_radians(std::f64::consts::PI), 1 << 31);
372        assert!((angle_to_radians(1 << 30) - std::f64::consts::FRAC_PI_2).abs() < 1e-15);
373    }
374
375    #[test]
376    fn invalid_iteration_counts() {
377        assert!(Cordic::new(0).is_err());
378        assert!(Cordic::new(31).is_err());
379        assert!(Cordic::new(1).is_ok());
380        assert!(Cordic::new(30).is_ok());
381    }
382
383    // ------------------------------------------------------------ 64-bit
384
385    const LSB64: f64 = 1.0 / (1u64 << 62) as f64;
386
387    fn max_error64(c: &Cordic64, samples: u64) -> f64 {
388        let step = u64::MAX / samples;
389        let mut worst = 0.0f64;
390        let mut a = 12_345u64;
391        for _ in 0..samples {
392            let (s, co) = c.sin_cos_fixed(a);
393            let r = Cordic64::angle_to_radians(a);
394            worst = worst.max((s as f64 * LSB64 - r.sin()).abs()).max((co as f64 * LSB64 - r.cos()).abs());
395            a = a.wrapping_add(step);
396        }
397        worst
398    }
399
400    #[allow(clippy::needless_range_loop)]
401    #[test]
402    fn tables64_match_their_definitions_to_double_precision() {
403        assert_eq!(ATAN_BAM_64[0], 1 << 61, "atan(1) is exactly an eighth of a turn");
404        for (i, &t) in ATAN_BAM_64.iter().enumerate() {
405            let want = (0.5f64.powi(i as i32)).atan() / TAU * 2f64.powi(64);
406            assert!((t as f64 - want).abs() <= want * 4e-16 + 1.0, "atan table entry {i}");
407        }
408        assert_eq!(*ATAN_BAM_64.last().unwrap(), 1);
409        for n in 1..=62usize {
410            let gain: f64 = (0..n).map(|i| (1.0 + 0.25f64.powi(i as i32)).sqrt()).product();
411            let want = 2f64.powi(62) / gain;
412            assert!((INV_GAIN_Q62[n] as f64 - want).abs() <= want * 1e-15 + 1.0, "gain table entry {n}");
413        }
414        assert_eq!(INV_GAIN_Q62[0], 1 << 62);
415    }
416
417    #[test]
418    fn double_precision_accuracy_at_52_iterations() {
419        let c = Cordic64::new(Cordic64::DEFAULT_ITERATIONS).unwrap();
420        assert_eq!(c.iterations(), 52);
421        // The reference itself carries ~1e-15 of error: it converts the 64-bit angle to f64
422        // radians. The exact-integer tests below resolve far smaller errors.
423        let err = max_error64(&c, 40_000);
424        assert!(err < 1.5e-15, "max error {err}");
425        let full = max_error64(&Cordic64::new(62).unwrap(), 40_000);
426        assert!(full < 1.5e-15, "max error {full}");
427    }
428
429    /// Exact integer checks that need no floating-point reference, so they can see errors far
430    /// below double precision.
431    #[test]
432    fn identities_hold_beyond_double_precision() {
433        let c = Cordic64::new(62).unwrap();
434        let unit = 1i128 << 124;
435        let mut seed = 0x1234_5678_9ABC_DEF0u64;
436        let mut next = || {
437            seed ^= seed << 13;
438            seed ^= seed >> 7;
439            seed ^= seed << 17;
440            seed
441        };
442        let (mut worst_radial, mut worst_angle) = (0.0f64, 0.0f64);
443        for _ in 0..4000 {
444            let (a, b) = (next(), next());
445            let (sa, ca) = c.sin_cos_fixed(a);
446            let (sb, cb) = c.sin_cos_fixed(b);
447            let (sab, _) = c.sin_cos_fixed(a.wrapping_add(b));
448            // Radial error: |(s, c)| should be 1.
449            let norm = sa as i128 * sa as i128 + ca as i128 * ca as i128;
450            worst_radial = worst_radial.max((norm - unit).abs() as f64 / unit as f64 / 2.0);
451            // Angle addition: sin(a+b) = sin a cos b + cos a sin b.
452            let lhs = sa as i128 * cb as i128 + ca as i128 * sb as i128;
453            let rhs = (sab as i128) << 62;
454            worst_angle = worst_angle.max((lhs - rhs).abs() as f64 / unit as f64);
455        }
456        assert!(worst_radial < 2e-17, "radial error {worst_radial:e}");
457        assert!(worst_angle < 5e-17, "angle-addition error {worst_angle:e}");
458    }
459
460    #[test]
461    fn error_shrinks_geometrically_with_64_bit_words() {
462        let errs: Vec<f64> = [8u32, 16, 24, 32, 40, 48].iter().map(|&n| max_error64(&Cordic64::new(n).unwrap(), 4001)).collect();
463        for w in errs.windows(2) {
464            assert!(w[1] < w[0] * 0.02, "{errs:?}");
465        }
466        assert!(errs[3] < 1e-9 && errs[5] < 2e-14, "{errs:?}");
467    }
468
469    #[test]
470    fn wide_words_do_better_than_narrow_ones() {
471        let narrow = max_error(&Cordic32::new(30).unwrap(), 1_000_003);
472        let wide = max_error64(&Cordic64::new(52).unwrap(), 4001);
473        assert!(wide * 1e5 < narrow, "{wide} vs {narrow}");
474    }
475
476    #[test]
477    fn quadrants_symmetry_and_unit_magnitude_64() {
478        let c = Cordic64::new(62).unwrap();
479        let near = |got: i64, want: i64| (got - want).abs() <= 64;
480        let one = Cordic64::ONE;
481        let (s, co) = c.sin_cos_fixed(0);
482        assert!(near(s, 0) && near(co, one));
483        let (s, co) = c.sin_cos_fixed(1 << 62);
484        assert!(near(s, one) && near(co, 0));
485        let (s, co) = c.sin_cos_fixed(1 << 63);
486        assert!(near(s, 0) && near(co, -one));
487        let (s, co) = c.sin_cos_fixed(3 << 62);
488        assert!(near(s, -one) && near(co, 0));
489        for a in [123_456_789u64, 0x9E37_79B9_7F4A_7C15, 0xDEAD_BEEF_0000_0001, u64::MAX - 5] {
490            let (s0, c0) = c.sin_cos_fixed(a);
491            let (s1, c1) = c.sin_cos_fixed(a.wrapping_add(1 << 62));
492            assert!((s1 - c0).abs() <= 128 && (c1 + s0).abs() <= 128, "angle {a}");
493            let mag = ((s0 as f64).powi(2) + (c0 as f64).powi(2)).sqrt() * LSB64;
494            assert!((mag - 1.0).abs() < 1e-15);
495        }
496    }
497
498    #[test]
499    fn float_wrappers_and_angle_conversion_64() {
500        let c = Cordic64::new(52).unwrap();
501        for k in -300..=300 {
502            let a = k as f64 * 0.0271;
503            let (s, co) = c.sin_cos(a);
504            assert!((s - a.sin()).abs() < 5e-15 && (co - a.cos()).abs() < 5e-15, "angle {a}");
505        }
506        assert_eq!(Cordic64::angle_from_turns(0.25), 1 << 62);
507        assert_eq!(Cordic64::angle_from_turns(-0.25), 3 << 62);
508        assert_eq!(Cordic64::angle_from_turns(1.0), 0);
509        assert_eq!(Cordic64::angle_from_radians(std::f64::consts::PI), 1 << 63);
510        assert!((Cordic64::angle_to_radians(1 << 62) - std::f64::consts::FRAC_PI_2).abs() < 1e-15);
511        assert!((c.gain() - 1.646760258121066).abs() < 1e-12);
512    }
513
514    #[test]
515    fn invalid_iteration_counts_64() {
516        assert!(Cordic64::new(0).is_err());
517        assert!(Cordic64::new(63).is_err());
518        assert!(Cordic64::new(1).is_ok() && Cordic64::new(62).is_ok());
519        // The 32-bit alias is unchanged.
520        let _: Cordic = Cordic::new(30).unwrap();
521        assert_eq!(Cordic::MAX_ITERATIONS, 30);
522    }
523}