My apologies if the following is no longer applicable to newer versions of CUDA. I am still on 9.2 at the moment. It is also possible that I have posted something essentially similar previously. I found this as apparent work-in-progress in a folder from 2017 while cleaning up my CUDA code repository.
roundf()
is one of those functions one uses rarely, as it was a late addition to the C++ language (inherited from C99). But every once in a while one needs this to avoid artifacts caused by the rounding mode “to nearest or even” used by rintf()
. The rounding mode used by roundf()
is similar in that it rounds to nearest, but it always rounds tie cases away from zero:
rintf roundf
-------------------------
3.5 4 4
4.5 4 5
5.5 6 6
6.5 6 7
While the GPU hardware directly supports the rounding modes used by truncf
, floorf
, ceilf
, and rintf
, it does not support the rounding mode used by roundf
. Therefore, roundf
compiles to an instruction sequence (consisting of eight instructions on most architectures) that emulates the required functionality.
The following replacement accomplishes this in only four instructions:
/*
Copyright (c) 2020, 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.
*/
/* Forces the sign of b onto the positive number a */
__device__ float copysignf_pos (float a, float b)
{
int ia = __float_as_int (a);
int ib = __float_as_int (b);
return __int_as_float (ia | (ib & 0x80000000));
}
/* Round to nearest, ties away from zero */
__device__ float my_roundf (float a)
{
const float rndofs = 0.49999997f; // 0x1.fffffep-2
return truncf (a + copysignf_pos (rndofs, a));
}
Obviously, analogous code can be constructed for the double-precision version round()
.