Monday, December 7, 2009

Square Root Rounding

Since CLDC 1.1 Java ME applications can use floating point operations like sin, cos, tan, sqrt, etc. All these methods are available at java.lang.Math class.

Some applications needs square root floating point precision and will have to use double variables. Other applications need only an approximation and this is what I present here.

Lets first take a look at how I create my square pyramid. To start we draw two colums with the base number and its square:








BaseSquare
00
11
24
39
416


Now we place all other numbers between the squares.








BaseSquare and other numbers
0
      values <= 0   
1
          1  2         
2
       3  4  5  6      
3
    7  8  9 10 11 12   
4
13 14 15 16 17 18 19 20


The square root approximation of these numbers is the same as the square root of the center value. For example, sqrtRound(7) == 3, sqrtRound(6) == 2.

Below is the source code:

public static int sqrtRound (int value) {
if (value <= 0) {
return 0;
}

int i = 1;
int j = 2;

// search for range where value is between two square values
while ((i * i) <= value && value > (j * j)) {
i++;
j++;
}

int d = (j * j) - (i * i) + 1;

if ((value - (i * i)) < (d / 2)) { // round down
return i;
} else { // round up
return j;
}
}

No comments: