Occasionally the square root of an integer is needed, that is ⌊√x⌋ . On many modern systems, the double-precision square root can be computed by the FPU in fewer than 20 cycles, so the square root of a 32-bit unsigned integer x
can be computed simply and efficiently by
__device__ uint32_t isqrt (uint32_t x)
{
return (uint32_t)sqrt ((double) x);
}
The throughput of double-precision operations on GPUs other than certain (semi-)professional models is very low, so the above implementation is not a good idea from a performance perspective. However, we can take advantage of the fact that all GPUs have a multifunction unit which can quickly compute a reciprocal square root to almost full single-precision accuracy, and multiplying that with the original argument yields the square root. The only thing left to do is to ensure that the correct floor is being computed, i.e. the largest integer less than or equal to the mathematical square root. The exhaustively tested implementation below puts this approach to work.
NOTE: It has been pointed out by @ AxelW that notwithstanding a successful exhaustive test, the line s = (uint32_t)fmaf (fr, fa, -0.5f) ;
invokes undefined behavior per the C++ standard when the function argument a
is zero.
/*
Copyright (c) 2021, Norbert Juffa
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/* compute floor (sqrt (a)) */
__device__ uint32_t isqrt (uint32_t a)
{
uint32_t s, rem;
float fa, fr;
/* Approximate square root accurately. Make sure it's an underestimate! */
fa = (float)a;
asm ("rsqrt.approx.ftz.f32 %0,%1; \n\t" : "=f"(fr) : "f"(fa));
s = (uint32_t)fmaf (fr, fa, -0.5f) ;
/* Make sure we got the floor correct */
rem = a - s * s;
if (rem >= (2 * s + 1)) s++;
return (a == 0) ? a : s;
}