Loading...
Searching...
No Matches
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
9#pragma once
10
22
23#include <stdint.h>
24
25#ifdef __cplusplus
26extern "C" {
27#endif
28
29#define SINI_PERIOD 0x8000
30#define SINI_MAX 0x1000
31#define SINI_MIN -0x1000
32
41static inline __attribute__((always_inline))
42int32_t _ihelp(int32_t x)
43{
44 int32_t y;
45 static const int32_t qN = 13,
46 qA = 12,
47 B = 19900,
48 C = 3516;
49
50 x = x << (31 - qN); /* Mask with PI */
51 x = x >> (31 - qN); /* Note: SIGNED shift! (to qN) */
52 x = x * x >> (2 * qN - 14); /* x=x^2 To Q14 */
53
54 y = B - (x * C >> 14); /* B - x^2*C */
55 y = (1 << qA) /* A - x^2*(B-x^2*C) */
56 - (x * y >> 16);
57
58 return y;
59}
60
68static inline int32_t fast_sini(int32_t x)
69{
70 static const int32_t qN = 13;
71
72 int32_t c = x << (30 - qN);
73 int32_t y = _ihelp(x - (1 << qN));
74
75 return c >= 0 ? y :-y;
76}
77
85static inline int32_t fast_cosi(int32_t x)
86{
87 static const int32_t qN = 13;
88
89 int32_t c = (x + (SINI_PERIOD >> 2)) << (30 - qN);
90 int32_t y = _ihelp(x);
91
92 return c >= 0 ? y :-y;
93}
94
101static inline unsigned sqrti(unsigned x)
102{
103 if (x <= 1) {
104 return x;
105 }
106
107 /* initial estimate */
108 unsigned y0 = x >> 1;
109 unsigned y1 = (y0 + x / y0) >> 1;
110
111 while (y1 < y0) {
112 y0 = y1;
113 y1 = (y0 + x / y0) >> 1;
114 }
115
116 return y0;
117}
118
127static inline uint32_t powi(unsigned x, unsigned y)
128{
129 uint32_t res = 1;
130
131 while (y--) {
132 res *= x;
133 }
134
135 return res;
136}
137
138#ifdef __cplusplus
139}
140#endif
141
static int32_t fast_sini(int32_t x)
A sine approximation via a fourth-order cosine approx.
Definition imath.h:68
static uint32_t powi(unsigned x, unsigned y)
Returns the value of x to the power of y.
Definition imath.h:127
static unsigned sqrti(unsigned x)
Square root of an integer.
Definition imath.h:101
static int32_t _ihelp(int32_t x)
Internal fast_sini/fast_cosi helper function.
Definition imath.h:42
#define SINI_PERIOD
Period of the fast_sini() function.
Definition imath.h:29
static int32_t fast_cosi(int32_t x)
A a fourth-order cosine approx.
Definition imath.h:85