Wednesday, December 1, 2010

Complex numbers in R

We sometimes encounter the situations of using complex numbers in our computation. For example, the square root of -1 can be denoted as 1*i. Complex numbers are implemented in the "base" package, it’s very easy to work with them. To construct a complex number x + iy, you use complex and specify its real and imaginary components explicitly as follows:

> x <- 2
> y <- 3
> z1 <- complex(real = x, imaginary = y)
> z1
[1] 2+3i

You can convert other objects to class "complex" using as.complex and test if an object is complex with is.comple

> z2 <- as.complex(-5)
> z2
[1] -5+0i
> is.complex(z2)
[1] TRUE

There are five basic mathematical operations that works on complex numbers, Re, Im, Mod, Arg, and Conj. First, you may want to extract the real and imaginary components of a complex number. You can do this using Re and Im, respectively. You can also find the modulus and complex argument of a complex number with Mod and Arg. Finally, you can take the complex conjugate of a complex number with the help of Conj.

> z3 <- complex(real = 1.3, imaginary = 6) 
> z3
[1] 1.3+6i
> Re(z3)
[1] 1.3
> Im(z3)
[1] 6
> Mod(z3)
[1] 6.139218
> Arg(z3)
[1] 1.357428
> Conj(z3)
[1] 1.3-6i

No comments:

Post a Comment