Friday, July 13, 2012

Finding number of decimals in data

I was asked for some GAMS code that produces the number of decimals provided in a table column. One should realize that a number like 0.1 is not exactly representable in binary, so we need to apply a certain tolerance. Here is what I came up with:

 sets    i /i1*i4/    j /j1*j4/ ; table data(i,j)      j1  j2     j3   j4 i1    1  0.1  0.01  100.0001 i2    2   2   0.01   0.01 i3    3   3   0.01   0.01 i4    4   4   0.01   0.01 ; * * find number of decimals * parameter numdec(j) 'number of decimals'; numdec(j)=0; loop((i,j),   while(abs(round(data(i,j),numdec(j))-data(i,j))>1.0e-15,     numdec(j) = numdec(j) + 1;   ) ); option data:5; option numdec:0; display data, numdec;

This produces:

 ----     27 PARAMETER data              j1          j2          j3          j4 i1     1.00000     0.10000     0.01000   100.00010 i2     2.00000     2.00000     0.01000     0.01000 i3     3.00000     3.00000     0.01000     0.01000 i4     4.00000     4.00000     0.01000     0.01000 ----     27 PARAMETER numdec  number of decimals j2 1,    j3 2,    j4 4

The first column has integers so the number of decimals is zero for that column.