Recently I needed to calculate the distance between two points. Not too difficult by itself, all you need is the square root of the X/Y distances:

`sqrt( (x1 - x2) * (x1-x2) + (y1 - y2) * (y1 - y2) )`

Thing is: CLDC 1.0 does not have a sqrt function, only CLDC 1.1 has… Plus, double and float are also both CLDC 1.1 – which is OK, since I only needed an integer value.

Wikipedia proved to be a good source of information, once more, so I found that I could implement the Newton Method to achieve the desired result. Since I had no luck finding appropriate code with Google that I could employ, I wrote the function myself. See code below.

`private int mysqrt(int a) {`
`    if (a <= 1) return a;`
`    int x = a / 2;`
`    do {`
`        x = (x + (a / x)) / 2;`
`    } while (x > (x + (a / x)) / 2);`
`    return x;`
`}`

Since the function should work with CLDC 1.0, all calculations are done with integers. The loss of precision can be addressed by multiplying the required number with 10^x, e.g. instead of calculating the square root of 2 calculate mysqrt(20000).

If the requested number is below 1, the function simply returns that value. Half the requested value is the first guess, which is refined in additional iteration as long as the next guess is small than the current one. Usually, after 6-7 iterations the result is found. If you need a faster computation, count the number of iterations and stop sooner. - © 2007 Codecat - powered by WordPress