Is it good to use double for == comparison and indexing?

In this answer said that it is best not to use ==

doubles when comparing.

When creating an increment variable in a loop for

using the notation start:step:stop

, the type will be double. If you want to use this loop variable for indexing and comparison ==

, could this cause problems because of floating point precision ?!

Should I use whole numbers? If so, is there a way to do this using notation s:s:s

?

Here's an example

a = rand(1, 5);

for ii = length(a):-1:1
  if (ii == 1)      % Comparing var of type double with ==
    b = 0;          
  else
    b = a(ii);      % Using double for indexing
  end

  ...               % Code

end

      

+3


source to share


2 answers


Note that the double floating point specification uses 52 bits to store the mantissa (the part after the decimal point) so that you can accurately represent any integer in the range

-4503599627370496 <= x <= 4503599627370496

      

Note that this is more than the int32 range that only

      -2147483648 <= x <= 2147483647

      



If you are just using double as a loop variable and only incrementing it in integer steps and you don't count above 4 503 599 627 370 496, then you can use double and use ==

doubles to compare.

One of the reasons people suggest not to use doublings is because you cannot accurately represent some common decimal numbers, for example. 0.1 has no precise representation as double. So if you are working with monetary values, it might be better to separately store the data as int and remember the scale factor of 10x or 100x or whatever.

Sometimes it is bad to compare comparing floating point numbers for equality because rounding problems can cause the two floats to not be equal even though the numbers are mathematically equal. This usually happens when the numbers are not accurately represented as floats, or when there is a significant size difference between the numbers, for example

>> 0.3 - 0.2 == 0.1
ans =
     0

      

+7


source


  • If you are indexing between integer bounds with integer strides (although the class of the variable is actually double

    ), can be used ==

    to compare with other integers.
  • You can specify indices if you really want to be safe.

For example:



for ii = int16(length(a):-1:1)
    if (ii == 1)
       b = 0;
    end
end

      

+3


source







All Articles