R Examples

R Program - Square Root of a Number



If a number is multiplied by itself (n*n), the final number will be the square of that number and finding the square root of a number is inverse operation of squaring the number. If x is the square root of y, it can be expressed as below:

square root

Alternatively, it can also be expressed as:

x2 = y

Method 1: Using exponential (**) operator

The exponential (**) operator of R can be used to calculate the square root of a number. Alternatively, the caret symbol (^) can also be used as exponential/power operator. See the example below for syntax.

x <- 16
y <- 25
x1 <- x**0.5
y1 <- y**0.5
sprintf("Square root of %f is %f", x, x1)
sprintf("Square root of %f is %f", y, y1)

The above code will give the following output:

[1] "Square root of 16.000000 is 4.000000"
[1] "Square root of 25.000000 is 5.000000"

Method 2: Using sqrt() method of math Module

The sqrt() method of math module can also be used to calculate square root of a number.

x <- 16
y <- 25
x1 <- sqrt(x)
y1 <- sqrt(y)
sprintf("Square root of %f is %f", x, x1)
sprintf("Square root of %f is %f", y, y1)

The above code will give the following output:

[1] "Square root of 16.000000 is 4.000000"
[1] "Square root of 25.000000 is 5.000000"