Working with different IEEE floating-point rounding modes in C++

前提是你 提交于 2019-12-11 07:31:15

问题


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:

  1. This is C++11, not C++98 (although in practice you could probably just use your system's <fenv.h> which is C99.
  2. It requires communicating with the compiler via #pragma 's
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!