Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 doubles but without all the digits on C

Tags:

c

compare

double

I want to compare 2 double but without all the digits. for example i have this double 1.548799778 and this 1.547990978 and I want to compare 1.xx from each. How can I "round" this double to 1.xx?? Thanks

like image 536
BlackM Avatar asked Nov 27 '11 11:11

BlackM


3 Answers

One technique will be using the trunc function like this:

double d1, d2;
d1 = 1.548799778;
d2 = 1.547990978;
if (trunc(d1*100) == trunc(d2*100)) {
   // do your thing
}

Using 100 because you want two decimal places. You can use other numbers if you want more or less decimal places.

like image 168
Pablo Santa Cruz Avatar answered Nov 09 '22 13:11

Pablo Santa Cruz


to compare that x and y are near enough, something like

(x==0.0 && y==0.0) || fabs(x-y)/max(fabs(x),fabs(y))<1e-6

to round x use floor(x) or ceil(x) as suggested by Jan Vorcak

Addenda: I'm not sure that it will work for NaN (the details give headache)

like image 27
Basile Starynkevitch Avatar answered Nov 09 '22 13:11

Basile Starynkevitch


Another possibility is to just use a comparison with tolerance.

 if (fabs(a - b) <= tolerance) { .... }

choose your tolerance on how much precision you want.

For example, you can choose tolerance to be 0.001 to use about the first 2 digits.

like image 32
Salvatore Previti Avatar answered Nov 09 '22 11:11

Salvatore Previti