[SOLVED] (int) Math.sqrt(n) much slower than (int) Math.floor(Math.sqrt(n))

Issue

I was looking at my code, hoping to improve its performance and then i saw this:

int sqrt = (int) Math.floor(Math.sqrt(n));

Oh, ok, i don’t really need the call to Math.floor, as casting the double returned from Math.sqrt(n) will be effectively flooring the number too (as sqrt will never return a negative number). So i went and dropped the call to Math.floor:

int sqrt = (int) Math.sqrt(n)

sat back and complacently watched the code run and perform roughly 10% ! worse than its previous version. This came to me as a shock. Any ideas anyone?

Math.floor javadocs: “Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.”

EDIT
in my case n is a long. Any chance cast-floor-sqrt would ever produce a different int than cast-sqrt? I personally can’t see why it ever would… all numbers involved are positive.

Solution

The Math.floor method just delegates the call to the StrictMath.floor method (as seen on java.lang.StrictMath‘s source code). This method is a native method. After this method the cast does not have to do anything because it is already a number that is equal to an integer (so no decimal places).

Maybe the native implementation of floor is faster than the cast of a double value to an int value.

Answered By – mvieghofer

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *