Suppose data is {3,2,7}. data.length is 3. This will compute sqrt((9+4+49)/3).

double sum=0;
// sum is now zero

for(int i=0; i<data.length; i++)
// Execute the following statement with i having each value starting from 0,
// incrementing by 1 each time (i++), as long as i remains less than 3.
    sum+= data[i]*data[i];
    // The sum+= statement is executed three times, with i each of 0, 1, and 2.
    // The first time adds 9 to sum getting 9
    // The second time adds 4 to sum getting 13
    // The third time adds 49 to sum, getting 62

double qmean = Math.sqrt(sum/data.length);
// make qmean equal to sqrt(62/3).

System.out.println(qmean);// Displays the final result.
Answer from Patricia Shanahan on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-math-sqrt-method
Java Math sqrt() Method - GeeksforGeeks
The Math.sqrt() method is a part of java.lang.Math package. This method is used to calculate the square root of a number. This method returns the square root of a given value of type double.
Published   May 13, 2025
🌐
W3Schools
w3schools.com › java › ref_math_sqrt.asp
Java Math sqrt() Method
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... System.out.println(Math.sqrt(0)); System.out.println(Math.sqrt(1)); System.out.println(Math.sqrt(9)); System.out.println(Math.sqrt(0.64)); System.out.println(Math.sqrt(-9));
Discussions

arrays - Math.pow and Math.sqrt in Java - Stack Overflow
That's just simple math, translating the formulas for geometric mean and quadratic mean (RMS) into Java code. More on stackoverflow.com
🌐 stackoverflow.com
java Math. Sqrt
Just break the equation into its parts. (Math.pow(..., n) gives you the n-th power) double a = Math.pow(x2 - x1, 2) double b = Math.pow(y2 - y1, 2) To calculate the root you can then use Math.sqrt(...) To get the final result double a = Math.pow(x2 - x1, 2); double b = Math.pow(y2 - y1, 2); double distance = Math.sqrt(a + b); More on reddit.com
🌐 r/java
3
0
September 17, 2014
Why we can't use int or float with Math.sqrt ?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
9
1
September 17, 2023
java - (int) Math.sqrt(n) much slower than (int) Math.floor(Math.sqrt(n)) - Stack Overflow
Oh, ok, i don't really need the ... too (as sqrt will never return a negative number). So i went and dropped the call to Math.floor: ... 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 ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Math.html
Math (Java Platform SE 8 )
October 20, 2025 - Returns sqrt(x2 +y2) without intermediate overflow or underflow.
🌐
Scaler
scaler.com › home › topics › math.sqrt() in java
Math.sqrt() Method in Java
April 28, 2024 - Math.sqrt() method of java.lang package is used to find a given number's correctly rounded and positive square root in Java.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › Math › sqrt
Java Math sqrt() - Calculate Square Root | Vultr Docs
September 27, 2024 - The Math.sqrt() function in Java efficiently computes the square root of a number and is essential in various professional fields requiring mathematical calculations.
Find elsewhere
🌐
Reddit
reddit.com › r/javahelp › why we can't use int or float with math.sqrt ?
r/javahelp on Reddit: Why we can't use int or float with Math.sqrt ?
September 17, 2023 -

I'm a beginner and came to calculating square root of a number part. Lesson says I need to use double with Math.sqrt
int number = 42;
double squareRoot = Math.sqrt(number);
and I was curious why we can't use int or float. I searched on google but couldn't find an answer.

Top answer
1 of 2
6

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.

2 of 2
1

I cannot reproduce the same results. Using this simple Java code below, the function without the call to Math.floor is consistently faster:

with floor elapsed milliseconds: 7354
without floor elapsed milliseconds: 4252


public class TestCast {
    private static final int REPS = Integer.MAX_VALUE / 4;

    private static void withFloor() {
        long sum = 0;
        long start = System.currentTimeMillis();
        for (int i = REPS;  i != 0;  --i) {
            sum += (int)Math.floor(Math.sqrt(i));
        }
        long end = System.currentTimeMillis();
        long elapsed = end - start;
        System.out.println("with floor elapsed milliseconds: " + elapsed);
        System.out.println(sum);
    }

    private static void withoutFloor() {
        long sum = 0;
        long start = System.currentTimeMillis();
        for (int i = REPS;  i != 0;  --i) {
            sum += (int)Math.sqrt(i);
        }
        long end = System.currentTimeMillis();
        long elapsed = end - start;
        System.out.println("without floor elapsed milliseconds: " + elapsed);
        System.out.println(sum);
    }

    public static void main(String[] args) {
        withFloor();
        withoutFloor();
    }
}

Also, looking at the disassembled byte code we can clearly see the call to Math.floor in the first function and no call in the second. There must be something else going on in your code. Perhaps you can post your code or a shortened version of it that shows the results that you are seeing.

private static void withFloor();
  Code:
     0: lconst_0      
     1: lstore_0      
     2: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
     5: lstore_2      
     6: ldc           #3                  // int 536870911
     8: istore        4
    10: iload         4
    12: ifeq          35
    15: lload_0       
    16: iload         4
    18: i2d           
    19: invokestatic  #4                  // Method java/lang/Math.sqrt:(D)D
    22: invokestatic  #5                  // Method java/lang/Math.floor:(D)D
    25: d2i           
    26: i2l           
    27: ladd          
    28: lstore_0      
    29: iinc          4, -1
    32: goto          10
    35: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
    38: lstore        4
    40: lload         4
    42: lload_2       
    43: lsub          
    44: lstore        6
    46: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
    49: new           #7                  // class java/lang/StringBuilder
    52: dup           
    53: invokespecial #8                  // Method java/lang/StringBuilder."<init>":()V
    56: ldc           #9                  // String with floor elapsed milliseconds: 
    58: invokevirtual #10                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    61: lload         6
    63: invokevirtual #11                 // Method java/lang/StringBuilder.append:(J)Ljava/lang/StringBuilder;
    66: invokevirtual #12                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    69: invokevirtual #13                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    72: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
    75: lload_0       
    76: invokevirtual #14                 // Method java/io/PrintStream.println:(J)V
    79: return        

private static void withoutFloor();
  Code:
     0: lconst_0      
     1: lstore_0      
     2: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
     5: lstore_2      
     6: ldc           #3                  // int 536870911
     8: istore        4
    10: iload         4
    12: ifeq          32
    15: lload_0       
    16: iload         4
    18: i2d           
    19: invokestatic  #4                  // Method java/lang/Math.sqrt:(D)D
    22: d2i           
    23: i2l           
    24: ladd          
    25: lstore_0      
    26: iinc          4, -1
    29: goto          10
    32: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
    35: lstore        4
    37: lload         4
    39: lload_2       
    40: lsub          
    41: lstore        6
    43: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
    46: new           #7                  // class java/lang/StringBuilder
    49: dup           
    50: invokespecial #8                  // Method java/lang/StringBuilder."<init>":()V
    53: ldc           #15                 // String without floor elapsed milliseconds: 
    55: invokevirtual #10                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
    58: lload         6
    60: invokevirtual #11                 // Method java/lang/StringBuilder.append:(J)Ljava/lang/StringBuilder;
    63: invokevirtual #12                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
    66: invokevirtual #13                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
    69: getstatic     #6                  // Field java/lang/System.out:Ljava/io/PrintStream;
    72: lload_0       
    73: invokevirtual #14                 // Method java/io/PrintStream.println:(J)V
    76: return        
🌐
CodeGym
codegym.cc › java blog › java math › math.sqrt method - square root in java
Math.sqrt Method - Square Root in Java
February 18, 2025 - If you find yourself needing super-precise computations, explore BigDecimal or specialized libraries. And if you only need moderate accuracy—like finding the area of a circle for a casual project—Math.sqrt() with double will serve you well. Keep practicing, and happy coding! This was a brief rundown on finding a square root of a number in Java.
Top answer
1 of 4
40

When you install a JDK the source code of the standard library can be found inside src.zip. This won't help you for StrictMath, though, as StrictMath.sqrt(double) is implemented as follows:

public static native double sqrt(double a);

So it's really just a native call and might be implemented differently on different platforms by Java.

However, as the documentation of StrictMath states:

To help ensure portability of Java programs, the definitions of some of the numeric functions in this package require that they produce the same results as certain published algorithms. These algorithms are available from the well-known network library netlib as the package "Freely Distributable Math Library," fdlibm. These algorithms, which are written in the C programming language, are then to be understood as executed with all floating-point operations following the rules of Java floating-point arithmetic.

The Java math library is defined with respect to fdlibm version 5.3. Where fdlibm provides more than one definition for a function (such as acos), use the "IEEE 754 core function" version (residing in a file whose name begins with the letter e). The methods which require fdlibm semantics are sin, cos, tan, asin, acos, atan, exp, log, log10, cbrt, atan2, pow, sinh, cosh, tanh, hypot, expm1, and log1p.

So by finding the appropriate version of the fdlibm source, you should also find the exact implementation used by Java (and mandated by the specification here).

The implementation used by fdlibm is

static const double one = 1.0, tiny=1.0e-300;

double z;
int sign = (int) 0x80000000; 
unsigned r, t1, s1, ix1, q1;
int ix0, s0, q, m, t, i;

ix0 = __HI(x); /* high word of x */
ix1 = __LO(x); /* low word of x */

/* take care of Inf and NaN */
if ((ix0 & 0x7ff00000) == 0x7ff00000) {            
    return x*x+x; /* sqrt(NaN) = NaN, 
                     sqrt(+inf) = +inf,
                     sqrt(-inf) = sNaN */
} 

/* take care of zero */
if (ix0 <= 0) {
    if (((ix0&(~sign)) | ix1) == 0) {
        return x; /* sqrt(+-0) = +-0 */
    } else if (ix0 < 0) {
        return (x-x) / (x-x); /* sqrt(-ve) = sNaN */
    }
}

/* normalize x */
m = (ix0 >> 20);
if (m == 0) { /* subnormal x */
    while (ix0==0) {
        m -= 21;
        ix0 |= (ix1 >> 11); ix1 <<= 21;
    }
    for (i=0; (ix0&0x00100000)==0; i++) {
        ix0 <<= 1;
    }
    m -= i-1;
    ix0 |= (ix1 >> (32-i));
    ix1 <<= i;
}

m -= 1023; /* unbias exponent */
ix0 = (ix0&0x000fffff)|0x00100000;
if (m&1) { /* odd m, double x to make it even */
    ix0 += ix0 + ((ix1&sign) >> 31);
    ix1 += ix1;
}

m >>= 1; /* m = [m/2] */

/* generate sqrt(x) bit by bit */
ix0 += ix0 + ((ix1 & sign)>>31);
ix1 += ix1;
q = q1 = s0 = s1 = 0; /* [q,q1] = sqrt(x) */
r = 0x00200000; /* r = moving bit from right to left */

while (r != 0) {
    t = s0 + r; 
    if (t <= ix0) { 
        s0 = t+r; 
        ix0 -= t; 
        q += r; 
    } 
    ix0 += ix0 + ((ix1&sign)>>31);
    ix1 += ix1;
    r>>=1;
}

r = sign;
while (r != 0) {
    t1 = s1+r; 
    t = s0;
    if ((t<ix0) || ((t == ix0) && (t1 <= ix1))) { 
        s1 = t1+r;
        if (((t1&sign) == sign) && (s1 & sign) == 0) {
            s0 += 1;
        }
        ix0 -= t;
        if (ix1 < t1) {
            ix0 -= 1;
        }
        ix1 -= t1;
        q1  += r;
    }
    ix0 += ix0 + ((ix1&sign) >> 31);
    ix1 += ix1;
    r >>= 1;
}

/* use floating add to find out rounding direction */
if((ix0 | ix1) != 0) {
    z = one - tiny; /* trigger inexact flag */
    if (z >= one) {
        z = one+tiny;
        if (q1 == (unsigned) 0xffffffff) { 
            q1=0; 
            q += 1;
        }
    } else if (z > one) {
        if (q1 == (unsigned) 0xfffffffe) {
            q+=1;
        }
        q1+=2; 
    } else
        q1 += (q1&1);
    }
}

ix0 = (q>>1) + 0x3fe00000;
ix1 =  q 1>> 1;
if ((q&1) == 1) ix1 |= sign;
ix0 += (m <<20);
__HI(z) = ix0;
__LO(z) = ix1;
return z;
2 of 4
14

Since I happen to have OpenJDK lying around, I'll show its implementation here.

In jdk/src/share/native/java/lang/StrictMath.c:

JNIEXPORT jdouble JNICALL
Java_java_lang_StrictMath_sqrt(JNIEnv *env, jclass unused, jdouble d)
{
    return (jdouble) jsqrt((double)d);
}

jsqrt is defined as sqrt in jdk/src/share/native/java/lang/fdlibm/src/w_sqrt.c (the name is changed through the preprocessor):

#ifdef __STDC__
        double sqrt(double x)           /* wrapper sqrt */
#else
        double sqrt(x)                  /* wrapper sqrt */
        double x;
#endif
{
#ifdef _IEEE_LIBM
        return __ieee754_sqrt(x);
#else
        double z;
        z = __ieee754_sqrt(x);
        if(_LIB_VERSION == _IEEE_ || isnan(x)) return z;
        if(x<0.0) {
            return __kernel_standard(x,x,26); /* sqrt(negative) */
        } else
            return z;
#endif
}

And __ieee754_sqrt is defined in jdk/src/share/native/java/lang/fdlibm/src/e_sqrt.c as:

#ifdef __STDC__
static  const double    one     = 1.0, tiny=1.0e-300;
#else
static  double  one     = 1.0, tiny=1.0e-300;
#endif

#ifdef __STDC__
        double __ieee754_sqrt(double x)
#else
        double __ieee754_sqrt(x)
        double x;
#endif
{
        double z;
        int     sign = (int)0x80000000;
        unsigned r,t1,s1,ix1,q1;
        int ix0,s0,q,m,t,i;

        ix0 = __HI(x);                  /* high word of x */
        ix1 = __LO(x);          /* low word of x */

    /* take care of Inf and NaN */
        if((ix0&0x7ff00000)==0x7ff00000) {
            return x*x+x;               /* sqrt(NaN)=NaN, sqrt(+inf)=+inf
                                           sqrt(-inf)=sNaN */
        }
    /* take care of zero */
        if(ix0<=0) {
            if(((ix0&(~sign))|ix1)==0) return x;/* sqrt(+-0) = +-0 */
            else if(ix0<0)
                return (x-x)/(x-x);             /* sqrt(-ve) = sNaN */
        }
    /* normalize x */
        m = (ix0>>20);
        if(m==0) {                              /* subnormal x */
            while(ix0==0) {
                m -= 21;
                ix0 |= (ix1>>11); ix1 <<= 21;
            }
            for(i=0;(ix0&0x00100000)==0;i++) ix0<<=1;
            m -= i-1;
            ix0 |= (ix1>>(32-i));
            ix1 <<= i;
        }
        m -= 1023;      /* unbias exponent */
        ix0 = (ix0&0x000fffff)|0x00100000;
        if(m&1){        /* odd m, double x to make it even */
            ix0 += ix0 + ((ix1&sign)>>31);
            ix1 += ix1;
        }
        m >>= 1;        /* m = [m/2] */

    /* generate sqrt(x) bit by bit */
        ix0 += ix0 + ((ix1&sign)>>31);
        ix1 += ix1;
        q = q1 = s0 = s1 = 0;   /* [q,q1] = sqrt(x) */
        r = 0x00200000;         /* r = moving bit from right to left */

        while(r!=0) {
            t = s0+r;
            if(t<=ix0) {
                s0   = t+r;
                ix0 -= t;
                q   += r;
            }
            ix0 += ix0 + ((ix1&sign)>>31);
            ix1 += ix1;
            r>>=1;
        }

        r = sign;
        while(r!=0) {
            t1 = s1+r;
            t  = s0;
            if((t<ix0)||((t==ix0)&&(t1<=ix1))) {
                s1  = t1+r;
                if(((t1&sign)==sign)&&(s1&sign)==0) s0 += 1;
                ix0 -= t;
                if (ix1 < t1) ix0 -= 1;
                ix1 -= t1;
                q1  += r;
            }
            ix0 += ix0 + ((ix1&sign)>>31);
            ix1 += ix1;
            r>>=1;
        }

    /* use floating add to find out rounding direction */
        if((ix0|ix1)!=0) {
            z = one-tiny; /* trigger inexact flag */
            if (z>=one) {
                z = one+tiny;
                if (q1==(unsigned)0xffffffff) { q1=0; q += 1;}
                else if (z>one) {
                    if (q1==(unsigned)0xfffffffe) q+=1;
                    q1+=2;
                } else
                    q1 += (q1&1);
            }
        }
        ix0 = (q>>1)+0x3fe00000;
        ix1 =  q1>>1;
        if ((q&1)==1) ix1 |= sign;
        ix0 += (m <<20);
        __HI(z) = ix0;
        __LO(z) = ix1;
        return z;
}

There are copious comments in the file explaining the methods used, which I have omitted for (semi-) brevity. Here's the file in Mercurial (I hope this is the right way to link to it).

🌐
Programiz
programiz.com › java-programming › library › math › sqrt
Java Math sqrt()
Become a certified Java programmer. Try Programiz PRO! ... The sqrt() method returns the square root of the specified number. class Main { public static void main(String[] args) { // compute square root of 25 System.out.println(Math.sqrt(25)); } } // Output: 5.0
🌐
Codecademy
codecademy.com › docs › java › math methods › .sqrt()
Java | Math Methods | .sqrt() | Codecademy
September 3, 2022 - The Math.sqrt() method returns the positive, properly rounded square root of a double-type value. ... Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
🌐
YouTube
youtube.com › watch
Math Methods in Java (Math.pow, Math.sqrt, etc) - YouTube
Learn what the Math method is used for in Java, and understand how Math.abs, Math.pow, Math.sqrt, and an insane amount of other methods can be used to enhan...
Published   March 28, 2022
🌐
Dot Net Perls
dotnetperls.com › sqrt-java
Math.sqrt Method - Java
In mathematics, a square root maps the area of a square to the length of its side. In Java we use the Math class to compute square roots. With this method, we receive a double. For programs that call Math.sqrt many times, a lookup table cache can be used.
🌐
CodeAhoy
codeahoy.com › java › Math-Sqrt-method-JI_13
Java Math.sqrt() Method with Examples | CodeAhoy
October 12, 2019 - As we can see, it takes an argument of type double and returns it’s rounded square root, also as a double. Note just like all other methods on the Math class, Math.sqrt(…) is a static method so you can call it directly on the Math class.