5

I'm in the process of porting a windows program to linux, and have gotten stumped on piece of msvc-specific code that seems to check for floating point operations that has given a denormal or inexact result. I'm very much unsure on how to implement it in a robust manner. I should add that I'm fairly inexperienced when it comes to both linux-specific programming and very low-level operations like these.

Specifically, the part that gives me trouble is the following:

  if ( _statusfp() & ( _SW_INEXACT | _SW_DENORMAL) )
  {
     ... portable stuff ...
  }

  _clearfp();

While fenv.h seems to give the ability to both clear the status flag and check for the inexact flag, it does not seem to provide any assistance in checking the denormal flag. Furthermore, I have had it suggested to me that gcc might handle floating point operations differently enough that a simple straight port of this piece of code may not be possible. I'd be grateful for any assistance in this.

If it is relevant, this is used in a very heavy number crunching part of the program where performance matter.

Edit: The flag in fenv.h called FE_UNDERFLOW seems to be raised when a denormal result is generated according to http://en.cppreference.com/w/cpp/numeric/fenv/FE_exceptions , but have seen several other sources state that it is raised only when the result is too small even for a subnormal. Will run tests to see if it does what I need it too and and answer myself if so.

Pierre Andersson
  • 320
  • 2
  • 12
  • 1
    Does this help? http://stackoverflow.com/questions/16849009/in-the-linux-is-or-not-exists-some-functions-be-similar-to-clearfp-and-stat – doctorlove Jun 20 '13 at 15:28

2 Answers2

1

Is C++11 an option for you? If so, perhaps you could call std::isnormal on the result, see e.g. http://en.cppreference.com/w/cpp/numeric/math/isnormal .

Saran Tunyasuvunakool
  • 1,064
  • 1
  • 9
  • 23
  • Looks like you can get it from Boost even if you don't have C++11: http://www.boost.org/doc/libs/1_41_0/libs/math/doc/sf_and_dist/html/math_toolkit/utils/fpclass.html – Mark Ransom Jun 24 '13 at 22:49
  • Sorry, this code base still needs to compile for C++03 for now. In additiona, this operation seems to detect if any denormal result has been yielded from a matrix multiplication. Iterating through the entire resulting matrix to see if any value is denormal would be my only options and most likely too slow, as this is a speed optimization in the first place. – Pierre Andersson Jun 26 '13 at 07:58
0

As said in the question, it seems that fenv.h has a flag FE_UNDERFLOW that on some architectures at least indicate a subnormal/denormal result. My own testing indicates that this seems to be the case on my test x86 architecture, so I will go ahead and use this for now unless a better solution is provided.

Pierre Andersson
  • 320
  • 2
  • 12