1

So im trying to compare 2 variables of type double. I have 2 arrays as follows:

double xPosRobots[1];
double Map[10][4] = {
        //{X1, Y1, X2, Y2}
        { 0, 3, 1, 4 }, //Grid 1
        { 1, 3, 2, 4 }, //Grid 2
        { 2, 3, 3, 4 }, //Grid 3
        { 3, 3, 4, 4 }, //Grid 4
        { 4, 3, 5, 4 }, //Grid 5
        { 5, 3, 6, 4 }, //Grid 6
        { 6, 3, 7, 4 }, //Grid 7
        { 6, 2, 7, 3 }, //Grid 8
        { 6, 1, 7, 2 }, //Grid 9
        { 6, 0, 7, 1 }  //Grid 10
    };

I have a for loop which increments the value in xPosRobots as follows:

for(int i=0; i<numRobots; i++){
   if(curGridRobot < nextGridRobot){
      xPosRobots[i] += robotSpeed * clock_period;
    }
}

where robotSpeed = 1 and clock_period = .005.

Then, i check the value of xPosRobots[i] to see if im crossing a boundary as follows:

if(xPosRobots[i] == Map[1][0]){
   //Crossing boundary
   //Update grid position
}

Right now, I only have 1 robot so xPosRobots[i] is only size 1, but I plan to add more robots so just leaving it flexible.

The issue im having is when im comparing xPosRobots with Map. Map[1][0] is set to 1 and it doesnt seem to trigger the if condition.

Likewise, when i tried to check it by doing if(xPosRobots[i] == 1) but this also doesnt seem to work since my code skips over it when when xPosRobots[i] = 1 and i think its probably due to the level of precision that comes with double? So my question is, what's a good way to go about doing this type of comparison when im dealing with 3 decimal point precision?

Javia1492
  • 862
  • 11
  • 28
  • equal comparing floating-point values is often a bad idea because it won't work most of the time. There's no double value exactly as 0.005, therefore the more you add, the more error you get [What is the most effective way for float and double comparison?](http://stackoverflow.com/q/17333/995714) – phuclv Feb 28 '17 at 02:30
  • Did you read my first link? Also read these https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ http://floating-point-gui.de/errors/comparison/ In general there's no best solution. It totally depends on what you intend to do. Sometimes the best way is to avoid floating-point math at all. For example store the values multiplied by 1000 so to add 0.005 you'll add 5 – phuclv Feb 28 '17 at 02:37
  • @LưuVĩnhPhúc I just ended up scaling everything up by a thousand. Doesnt make the program output make any sense initially but at least it works. Thanks of for the articles. – Javia1492 Feb 28 '17 at 07:07

0 Answers0