Testing for a float NaN results in a stack overflow

前端 未结 3 852
广开言路
广开言路 2020-12-31 11:40

C#, VS 2010

I need to determine if a float value is NaN.

Testing a float for NaN using

float.IsNaN(aFloatNumber) 

crashes

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-31 11:54

    I just wrote an example to reproduce the error: 1. Create a native C/C++ DLL which exports this function:

    extern "C" __declspec(dllexport)  int SetfloatingControlWord(void)
    {
        //unmask all the floating excetpions
        int err = _controlfp_s(NULL, 0, _MCW_EM);    
        return err;
    }
    

    2. Create a C# console program, which call the function SetfloatingControlWord, after that, do some floating operation such as NaN compare, then it leads to stack overflow.

     [DllImport("floatcontrol.dll")]
            public static extern Int32 SetfloatingControlWord();       
            static void Main(string[] args)
            {
               int n =   SetfloatingControlWord();          
               float fff = 0F;
               int iii = fff.CompareTo(float.NaN);
            }
    

    I encountered the same problem years ago, also, I noticed that after an .NET exception throws, everything works fine, it took me a while to figure out why and trace the code which changed the FPU.

    As the doc of function _controlfp_s says: By default, the run-time libraries mask all floating-point exceptions. The common language runtime (CLR) only supports the default floating-point precision, so CLR doesn't handle these kind exceptions.

    As MSDN says:By default, the system has all FP exceptions turned off. Therefore, computations result in NAN or INFINITY, rather than an exception.

    After NaN was introduced in IEEE 754 1985, it suppose that application software no longer need to handle the floating point exceptions.

提交回复
热议问题