matlab double comparison

前端 未结 3 1677
渐次进展
渐次进展 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      
    
    0 讨论(0)
  • 2020-12-10 18:19

    The reason is MATLAB truncated the numbers in the array to preserve only 4 digits after the decimal point when displaying,. That is, the real value of your array may be [10.600000000001, -10.99999999999, ...]. You are right, this is due to the internal representation of floating-point numbers in computer, which may cause tiny errors in the computations.

    Personally I think there are two solutions, one is approximate matching like you did, while the other is to round the array up first (say, with this tool from FileExchange), and then do exact matching.

    0 讨论(0)
  • 2020-12-10 18:25

    Create a MATLAB function file that will accept a modulo values (from 3 to 9; that is Z3 to Z9) and will output the least possible value describe by the modulo conditions.

    Sample Simulation:

    Z = [ 3 4 5 ]; % Modulo Z3, Z4, and Z5

    r = [ 2 1 4 ]; % Remainder Values

    Least Possible Value is 29.

    The Z inputs must be an array matrix ... where in you can type any number from 3 to 9 .... and you can type 3,4,5,6,7,8,9 in any order, in any pairings or groupings ...

    The r inputs should be equal to the number of z inputs too...

    the output should yield the least possible value though modulo conditions...

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