Comparing IEEE floats and doubles for equality

前端 未结 15 2356
南方客
南方客 2020-11-30 06:00

What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.

15条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 06:37

    If you are looking for two floats to be equal, then they should be identically equal in my opinion. If you are facing a floating point rounding problem, perhaps a fixed point representation would suit your problem better.

    Perhaps I should explain the problem better. In C++, the following code:

    #include 
    
    using namespace std;
    
    
    int main()
    {
      float a = 1.0;
      float b = 0.0;
    
      for(int i=0;i<10;++i)
      {
        b+=0.1;
      }
    
      if(a != b)
      {
        cout << "Something is wrong" << endl;
      }
    
      return 1;
    }
    

    prints the phrase "Something is wrong". Are you saying that it should?

提交回复
热议问题