R sqrt, nth roots


sqrt() function computes the square root of a numeric vector. x^(1/n) calculates the nth roots of x.

sqrt(x)


x: numeric or complex vector, array, x>=0

> sqrt(9)

[1] 3


> sqrt(-1)

[1] NaN
Warning message:
In sqrt(-1) : NaNs produced


Square root of complex number:

> sqrt(3+5i)

[1] 2.101303+1.189738i

To calculate the nth root:

> 8^(1/3)
[1] 2
> exp(log(8)/3)
[1] 2


Square root of vector:

> sqrt(c(4,9,16))

[1] 2 3 4


It can also calculate the square root of all elements in a matrix.

> A <- matrix(c(3,5,7,1,9,4),nrow=3,ncol=2)
> A
     [,1] [,2]
[1,]    3    1
[2,]    5    9
[3,]    7    4
> sqrt(A)
         [,1] [,2]
[1,] 1.732051    1
[2,] 2.236068    3
[3,] 2.645751    2


Let's plot the sqrt() function in [0, 10000]:

> x <- seq(0, 10000, by=1)
> plot(sqrt(x),typ="l",col="blue", xlab="x")
> text(4300, 60, labels="y = ")
> text(5000, 60, labels=expression(sqrt(x)))


endmemo.com © 2024  | Terms of Use | Privacy | Home