matlab double comparison

前端 未结 3 1697
渐次进展
渐次进展 2020-12-10 18:06

I am trying to compare an array of doubles to a scalar double for equality, but equality is never recognized under certain circumstances. I suspect that this has to do with

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 18:13

    Something is probably in single precision somewhere, and double elsewhere. The binary representation of e.g. 10.2 in each is different as they terminate after a different number of bits. Thus they are different:

    >> if (single(10.2) == 10.2) disp('honk'); end
    >> if (single(10.2) == single(10.2)) disp('honk'); end
    honk
    

    You'll need to check for equality within some small difference:

     eps = 0.001;
     result = abs(array-10.2) < eps;
    

    You can find the precision used in an array using whos:

    >> whos A
      Name      Size            Bytes  Class     Attributes
    
      A         1x2                 8  single      
    

提交回复
热议问题