Method: CMath.sqrt

Defined in:
lib/cmath.rb

.sqrt(z) ⇒ Object

Returns the non-negative square root of Complex.

CMath.sqrt(-1 + 0i) #=> 0.0+1.0i


130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/cmath.rb', line 130

def sqrt(z)
  begin
    if z.real?
      if z < 0
        Complex(0, RealMath.sqrt(-z))
      else
        RealMath.sqrt(z)
      end
    else
      if z.imag < 0 ||
          (z.imag == 0 && z.imag.to_s[0] == '-')
        sqrt(z.conjugate).conjugate
      else
        r = z.abs
        x = z.real
        Complex(RealMath.sqrt((r + x) / 2.0), RealMath.sqrt((r - x) / 2.0))
      end
    end
  rescue NoMethodError
    handle_no_method_error
  end
end