forked from esp8266/Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqrt32.cpp
60 lines (46 loc) · 1001 Bytes
/
sqrt32.cpp
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
52
53
54
55
56
57
58
59
60
#include <coredecls.h>
#include <stdint.h>
extern "C" {
uint32_t sqrt32 (uint32_t n)
{
// http://www.codecodex.com/wiki/Calculate_an_integer_square_root#C
// Another very fast algorithm donated by [email protected]
// (note: tested across the full 32 bits range, see comment below)
// 15 iterations (c=1<<15)
unsigned int c = 0x8000;
unsigned int g = 0x8000;
for(;;)
{
if (g*g > n)
g ^= c;
c >>= 1;
if (!c)
return g;
g |= c;
}
}
/*
* tested with:
*
#include <stdio.h>
#include <stdint.h>
#include <math.h>
int main (void)
{
for (uint32_t i = 0; ++i; )
{
uint32_t sr = sqrt32(i);
uint32_t ifsr = sqrt(i);
if (ifsr != sr)
printf("%d: i%d f%d\n", i, sr, ifsr);
if (!(i & 0xffffff))
{
printf("%i%% (0x%08x)\r", ((i >> 16) * 100) >> 16, i);
fflush(stdout);
}
}
printf("\n");
}
*
*/
};