Sparky1039 0 Posted November 1, 2012 Report Share Posted November 1, 2012 Unfortunately Boost C math library doesn't support the square root function for a data type greater than unsigned int. I'm looking for some suggestions or code examples on how to accomplish the square root of an unsigned long. Currently working on a project where the customer has requested code enhancements that calculate standard deviation of 12-bit ADC sensor readings. The averaged sum of squares value can be quite large hence the unsigned long data type. Any help would be appreciated. thx Sparky Quote Link to post Share on other sites
Reynard 0 Posted November 1, 2012 Report Share Posted November 1, 2012 Hi Sparky, This appears to be the standard method irrespective of data size (32, 16 0r 8). A quick Google search found it, and seems to work in SB. #include <system.h> typedef unsigned long uint32_t; uint32_t isqrt32 (uint32_t n) { uint32_t root, remainder, place; root = 0; remainder = n; place = 0x40000000; while (place > remainder) place = place >> 2; while (place) { if (remainder >= root + place) { remainder = remainder - root - place; root = root + (place << 1); } root = root >> 1; place = place >> 2; } return root; } void main() { uint32_t result; result = isqrt32(1234567890); } Cheers Reynard Quote Link to post Share on other sites
Sparky1039 0 Posted November 1, 2012 Author Report Share Posted November 1, 2012 Thanks Reynard. I went with this and it seems to work correctly and is very fast. However I may revert to the example you provided for the long term since it's more flexible for different data types. unsigned int sqrt32 (unsigned long n) { unsigned long c = 0x8000; unsigned long g = 0x8000; for(; { if(g * g > n) g ^= c; c >>= 1; if(c == 0) return g; g |= c; } } Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You are posting as a guest. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.