-1

Performance wise (C++), would it be faster (and or acceptable) to access an array using the number before the decimal place to reference the first row, and the number after the decimal place to reference the column?

For instance:

map<float,int> myarray;
myarray[1.0001]=4;
myarray[1.0002]=5;
myarray[1.0003]=2;
myarray[2.0001]=7;
myarray[2.0002]=6;
myarray[2.0003]=3;

vs.:

int myarray[100][1000];
myarray[1][1]=4;
myarray[1][2]=5;
myarray[1][3]=2;
myarray[2][1]=7;
myarray[2][2]=6;
myarray[2][3]=3;
  • https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Ignacio Vazquez-Abrams Mar 01 '18 at 03:25
  • Good luck in actually using the `map` to find items, all due to floating point values being approximations. – PaulMcKenzie Mar 01 '18 at 03:26
  • 1
    Aside from the correctness issues above, the map will be much slower - 2D lookup in an array is just a simple address computation and one pointer dereference. The map will generally require several comparisons and pointer chasing for each lookup. – happydave Mar 01 '18 at 03:28

1 Answers1

2

First, your approach is not going to work, except for a subset of specific decimal numbers that can be represented exactly as floats. For example, 1.0001 is actually represented as 1.00010001659393310546875, so if you compute your index, you may get a slightly different representation that is not going to match; that would yield a false negative on accessing map.

As far as performance is concerned, your map is going to be O(log2 n), while accessing 2D array is going to be O(1). Moreover, it is going to take more memory, too, because trees take space for tree nodes, while arrays are overhead-free.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523