Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Square Root Integer Operations Without Casting?

Tags:

java

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?

like image 471
user1427661 Avatar asked Mar 04 '13 22:03

user1427661


3 Answers

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.

like image 72
Patricia Shanahan Avatar answered Oct 23 '22 16:10

Patricia Shanahan


You can always use the Google Guava IntMath API.

final int sqrtX = IntMath.sqrt(x, RoundingMode.HALF_EVEN);
like image 44
Amir Afghani Avatar answered Oct 23 '22 15:10

Amir Afghani


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.

like image 1
OldCurmudgeon Avatar answered Oct 23 '22 16:10

OldCurmudgeon