1use lib_jsl_core::ErrorsJSL;
27use std::f64::consts::TAU;
28use std::sync::OnceLock;
29
30const 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
40const 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
100macro_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 pub const FRACTIONAL_BITS: u32 = $FRAC;
123 pub const ONE: $W = 1 << $FRAC;
125 pub const MAX_ITERATIONS: u32 = $MAX;
127 pub const DEFAULT_ITERATIONS: u32 = $DEF;
129
130 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 pub fn gain(&self) -> f64 {
145 (0..self.iterations).map(|i| (1.0 + 0.25f64.powi(i as i32)).sqrt()).product()
146 }
147
148 fn shr_round(v: $W, shift: u32) -> $W {
150 if shift == 0 { v } else { (v + (1 << (shift - 1))) >> shift }
151 }
152
153 pub fn sin_cos_fixed(&self, angle: $A) -> ($W, $W) {
156 let inv_gain = $INV[self.iterations as usize];
157 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 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 pub fn angle_from_turns(turns: f64) -> $A {
194 ((turns.rem_euclid(1.0) * 2f64.powi($ABITS)).round() as u128) as $A }
196
197 pub fn angle_from_radians(radians: f64) -> $A {
199 Self::angle_from_turns(radians / TAU)
200 }
201
202 pub fn angle_to_radians(angle: $A) -> f64 {
204 angle as f64 / 2f64.powi($ABITS) * TAU
205 }
206 }
207 };
208}
209
210define_cordic! {
211 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 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
239pub type Cordic = Cordic32;
241
242pub const FRACTIONAL_BITS: u32 = Cordic32::FRACTIONAL_BITS;
244pub const ONE: i32 = Cordic32::ONE;
246pub const MAX_ITERATIONS: u32 = Cordic32::MAX_ITERATIONS;
248
249pub fn angle_from_radians(radians: f64) -> u32 {
251 Cordic32::angle_from_radians(radians)
252}
253
254pub fn angle_from_turns(turns: f64) -> u32 {
256 Cordic32::angle_from_turns(turns)
257}
258
259pub fn angle_to_radians(angle: u32) -> f64 {
261 Cordic32::angle_to_radians(angle)
262}
263
264pub 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 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); 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); assert!(near(s, ONE) && near(co, 0));
322 let (s, co) = c.sin_cos_fixed(1 << 31); assert!(near(s, 0) && near(co, -ONE));
324 let (s, co) = c.sin_cos_fixed(3 << 30); assert!(near(s, -ONE) && near(co, 0));
326 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 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 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 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 #[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 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 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 let _: Cordic = Cordic::new(30).unwrap();
521 assert_eq!(Cordic::MAX_ITERATIONS, 30);
522 }
523}