floating point precision problem in comparisons

Hey all,

This is probably trivial, but I have some code that is supposed to compare the elements in two different dynamically allocated double arrays. Even though the elements are the same value, they aren't being recognised as the same. One array is filled using a get function in the netcdf & netcdfcpp header files and the other is filled by reading from a csv file & using atof().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
bool checkLatLon(timeZone& TZlat,timeZone& TZlon,FireWeatherMCIP& lat,FireWeatherMCIP& lon){
  bool same=true;
  for (int i=0;i<ROW;i++){
    for (int j=0;j<COL;j++){
      if (double(lat.data[0][i][j])!=double(TZlat.data[i][j])){
	cout<<"latitudes do not match at point indices: "<<i<<","<<j<<". lat="<<lat.data[0][i][j]<<" TZlat="<<TZlat.data[i][j]<<endl;
	same=false;
      }
      if (lon.data[0][i][j]!=TZlon.data[i][j]){
	cout<<"longitudes do not match at point indices: "<<i<<","<<j<<". lon="<<lon.data[0][i][j]<<" TZlon="<<TZlon.data[i][j]<<endl;
	same=false;
      }
    }
  }
  return same;
}


OUTPUT (just part of it...):

latitudes do not match at point indices: 90,72. lat=53.6658 TZlat=53.6658
longitudes do not match at point indices: 90,72. lon=-96.2045 TZlon=-96.2045
latitudes do not match at point indices: 90,73. lat=53.6622 TZlat=53.6622
longitudes do not match at point indices: 90,73. lon=-95.6741 TZlon=-95.6741
latitudes do not match at point indices: 90,74. lat=53.6567 TZlat=53.6567

I was thinking maybe one is signed vs. unsigned, but both latitude & longitude have + and - values. Any other ideas?
Last edited on
I believe this is caused by floating-point imprecision. Use an epsilon value and consider them "equal" if the difference between them is smaller than epsilon.
Last edited on
I agree with filipe's diagnosis.

Here's more reading: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17
Thanks! I don't know why I didn't think of that. It's been a few years since I really considered floating point precision.
Topic archived. No new replies allowed.