Usefulness of signaling NaN?

后端 未结 3 734
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 21:09

I\'ve recently read up quite a bit on IEEE 754 and the x87 architecture. I was thinking of using NaN as a \"missing value\" in some numeric calculation code I\'m working on

相关标签:
3条回答
  • 2020-12-04 21:37

    As I understand it, the purpose of signaling NaN is to initialize data structures, but, of course runtime initialization in C runs the risk of having the NaN loaded into a float register as part of initialization, thereby triggering the signal because the the compiler isn't aware that this float value needs to be copied using an integer register.

    I would hope that you could could initialize a static value with a signaling NaN, but even that would require some special handling by the compiler to avoid having it converted to a quiet NaN. You could perhaps use a bit of casting magic to avoid having it treated as a float value during initialization.

    If you were writing in ASM, this would not be an issue. but in C and especially in C++, I think you will have to subvert the type system in order to initialize a variable with NaN. I suggest using memcpy.

    0 讨论(0)
  • 2020-12-04 21:57

    Couldn't you just have a const uint64_t where the bits have been set to those of a signaling nan? as long as you treat it as an integer type, the signaling nan is not different from other integers. You could write it where you want through pointer-casting:

    Const uint64_t sNan = 0xfff0000000000000;
    Double[] myData;
    ...
    Uint64* copier = (uint64_t*) &myData[index];
    *copier=sNan | myErrorFlags;
    

    For info on the bits to set: https://www.doc.ic.ac.uk/~eedwards/compsys/float/nan.html

    0 讨论(0)
  • 2020-12-04 22:04

    Using special values (even NULL) can make your data a lot muddier and your code a lot messier. It would be impossible to distinguish between a QNaN result and a QNaN "special" value.

    You might be better maintaining a parallel data structure to track validity, or perhaps having your FP data in a different (sparse) data structure to only keep valid data.

    This is fairly general advice; special values are very useful in certain cases (e.g. really tight memory or performance constraints), but as the context grows larger they can cause more difficulty than they're worth.

    0 讨论(0)
提交回复
热议问题