imath.h
1 /*
2  * Copyright (C) 2023 ML!PA Consulting GmbH
3  *
4  * This file is subject to the terms and conditions of the GNU Lesser
5  * General Public License v2.1. See the file LICENSE in the top level
6  * directory for more details.
7  */
8 
21 #ifndef IMATH_H
22 #define IMATH_H
23 
24 #include <stdint.h>
25 
26 #ifdef __cplusplus
27 extern "C" {
28 #endif
29 
30 #define SINI_PERIOD 0x8000
31 #define SINI_MAX 0x1000
32 #define SINI_MIN -0x1000
42 static inline __attribute__((always_inline))
43 int32_t _ihelp(int32_t x)
44 {
45  int32_t y;
46  static const int32_t qN = 13,
47  qA = 12,
48  B = 19900,
49  C = 3516;
50 
51  x = x << (31 - qN); /* Mask with PI */
52  x = x >> (31 - qN); /* Note: SIGNED shift! (to qN) */
53  x = x * x >> (2 * qN - 14); /* x=x^2 To Q14 */
54 
55  y = B - (x * C >> 14); /* B - x^2*C */
56  y = (1 << qA) /* A - x^2*(B-x^2*C) */
57  - (x * y >> 16);
58 
59  return y;
60 }
61 
69 static inline int32_t fast_sini(int32_t x)
70 {
71  static const int32_t qN = 13;
72 
73  int32_t c = x << (30 - qN);
74  int32_t y = _ihelp(x - (1 << qN));
75 
76  return c >= 0 ? y :-y;
77 }
78 
86 static inline int32_t fast_cosi(int32_t x)
87 {
88  static const int32_t qN = 13;
89 
90  int32_t c = (x + (SINI_PERIOD >> 2)) << (30 - qN);
91  int32_t y = _ihelp(x);
92 
93  return c >= 0 ? y :-y;
94 }
95 
102 static inline unsigned sqrti(unsigned x)
103 {
104  if (x <= 1) {
105  return x;
106  }
107 
108  /* initial estimate */
109  unsigned y0 = x >> 1;
110  unsigned y1 = (y0 + x / y0) >> 1;
111 
112  while (y1 < y0) {
113  y0 = y1;
114  y1 = (y0 + x / y0) >> 1;
115  }
116 
117  return y0;
118 }
119 
128 static inline uint32_t powi(unsigned x, unsigned y)
129 {
130  uint32_t res = 1;
131 
132  while (y--) {
133  res *= x;
134  }
135 
136  return res;
137 }
138 
139 #ifdef __cplusplus
140 }
141 #endif
142 
143 #endif /* IMATH_H */
static int32_t fast_sini(int32_t x)
A sine approximation via a fourth-order cosine approx.
Definition: imath.h:69
static uint32_t powi(unsigned x, unsigned y)
Returns the value of x to the power of y.
Definition: imath.h:128
static unsigned sqrti(unsigned x)
Square root of an integer.
Definition: imath.h:102
static int32_t _ihelp(int32_t x)
Internal fast_sini/fast_cosi helper function.
Definition: imath.h:43
#define SINI_PERIOD
Period of the fast_sini() function.
Definition: imath.h:30
static int32_t fast_cosi(int32_t x)
A a fourth-order cosine approx.
Definition: imath.h:86