forked from parallella/pal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
p_sqrt.c
51 lines (45 loc) · 1.18 KB
/
p_sqrt.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <pal.h>
/**
*
* Calculates the square root of the input vector 'a'.
*
* This uses a method to approximate sqrt which only applies to IEEE 754 floating point numbers,
* described in [1]. The optimized magic constant is from Chris Lomont[2]
*
* References:
* 1: http://en.wikipedia.org/wiki/Fast_inverse_square_root
* 2: http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf
*
* @param a Pointer to input vector
*
* @param c Pointer to output vector
*
* @param n Size of 'a' and 'c' vector.
*
* @return None
*
*/
void p_sqrt_f32(const float *a, float *c, int n)
{
int i;
for (i = 0; i < n; i++) {
const float *pa = (a+i);
float *pc = (c+i);
float x;
union {
float f;
int32_t i;
} j;
float xhalf = 0.5f*(*pa);
j.f = *pa;
j.i = 0x5f375a86 - (j.i >> 1);
x = j.f;
// Newton steps, repeating this increases accuracy
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
// x contains the inverse sqrt
// Multiply the inverse sqrt by the input to get the sqrt
*pc = *pa * x;
}
}