The Math.sqrt()
function takes a double as an argument and returns a double. I'm working with a program that uses a perfect square grid in all circumstances, and I need to obtain the square root in integer form. Is the only way to do this to cast the argument as an int
and then return an int
-casted double?
The cast technique is much better than it may seem to be at first sight.
Conversion from int to double is exact.
Math.sqrt is specified, for normal positive numbers, to return "the double value closest to the true mathematical square root of the argument value". If the input was a perfect square int, the result will be an integer-valued double that is in the int range.
Similarly, conversion of that integer-valued double back to an int is also exact.
The net effect is that the cast technique does not introduce any rounding error in your situation.
If your program would otherwise benefit from use of the Guava intMath API, you can use that to do the square root, but I would not add dependency on an API just to avoid the cast.
You can always use the Google Guava IntMath API.
final int sqrtX = IntMath.sqrt(x, RoundingMode.HALF_EVEN);
If you will only ever compute the square root of a perfect square have you considered the option of pre-calculating them into a table? There are a limited number of integer perfect squares and most JVMs could hold all of them at once without much effort. If space is at a premium I am sure there would be some other option in this direction.
Although there are 65535 of them, if that is just too many you could store one in perhaps four and calculate the ones in between. After all (x+1)^2 = (x+1)(x+1) = x^2 + 2x + 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With