Ruby: Complex Numbers

By Xah Lee. Date: . Last updated: .

In Ruby, Complex number is represented by the object “Complex”. Example:

# -*- coding: utf-8 -*-
# ruby

# a complex number
cc = Complex(3, 4)

# when printed, it's shown as (x+y i)
p cc                            # (3+4i)

Get Real and Imaginary Parts

# -*- coding: utf-8 -*-
# ruby

# a complex number
cc = Complex(3, 4)

p cc.real                       # 3
p cc.imag                       # 4

Complex Number Addition, Multiplication

# -*- coding: utf-8 -*-
# ruby

# Complex number addition. (same as vector addition)
p Complex(2, 3) + Complex(4, 5)        #  (6+8i)

# multiplication of complex numbers
p Complex(1, 0) * Complex(0, 1)        #  (0+1i)

# scalar multiplication. That is, scale it.
p Complex(3, 4) * 2             #  (6+8j)

# adding a scalar adds to the real part
p Complex(3, 4) + 1             #  (4+4i)

Get Complex Number Length

# -*- coding: utf-8 -*-
# ruby

# length of a Complex number
p Complex(3, 4).abs             #  5.0

Get Complex Number Angle

# -*- coding: utf-8 -*-
# ruby

z1 = Complex(0, 1)

# get the angle. return in radians
p z1.angle                      #  1.5707963267948966

Convert To/From Rectangular, Polar Coordinates

# -*- coding: utf-8 -*-
# ruby

length = 1
angle = Math::PI

# polar to rectangular coordinate
p Complex.polar(length, angle)    # (-1+0.0i)
# -*- coding: utf-8 -*-
# ruby

z1 = Complex(0, 1)

# rectangular to polar coordinates. Returns a array [length, angle]
p z1.polar                      # [1, 1.5707963267948966]

http://www.ruby-doc.org/core-1.9.3/Complex.html

π and e

π is Math::PI

e is Math::E

# coding: utf-8
# ruby

# constant π
p Math::PI                      # 3.141592653589793

# constant e
p Math::E                       # 2.718281828459045

http://www.ruby-doc.org/core-1.9.3/Math.html