问题
Woe is me, I have to ensure the same floating-point results on a GPU and on the CPU. Ok, I understand IEEE has taken care of me and provided a nice standard to adhere to with several rounding options; and the CUDA part is sorted out (there are intrinsics for the different rounding modes), so that's just motivation.
But in host-side C++ code - how do I perform floating-point arithmetic in a specific rounding mode (and I mean in a specific statement, not throughout my translation unit)? Are there wrapper functions which use assembly under the hood? Is there a set of classes for floating point number proxies with the different rounding modes?
I'm also asking the same question about the translation-unit level. How do I make the compiler (gcc/clang/MSVC) default to a certain rounding mode when compiling a translation unit?
回答1:
Following a lead from @AndreasPapadopoulos , it looks like there is an official way to change the rounding mode:
int fesetround(int round)
int fegetround()
but there are several caveats:
- This is C++11, not C++98 (although in practice you could probably just use your system's
<fenv.h>
which is C99. - It requires communicating with the compiler via
#pragma
's - This switching might be slow.
I'm not sure how widely this is used in practice (and whether there are any nicer abstractions around it which are in more common use).
来源:https://stackoverflow.com/questions/39202713/working-with-different-ieee-floating-point-rounding-modes-in-c