Module: Roots

Includes:
Math
Included in:
Numeric
Defined in:
lib/roots.rb

Overview

file roots.rb

Instance Method Summary collapse

Instance Method Details

#root(n, k = 0) ⇒ Object

return kth (1..n) value of root n or default for k=0



142
143
144
145
146
147
148
149
150
151
152
# File 'lib/roots.rb', line 142

def root(n,k=0) # return kth (1..n) value of root n or default for k=0
  raise "Root  n not an integer >  0" unless n.kind_of?(Integer) && n>0
  raise "Index k not an integer >= 0" unless k.kind_of?(Integer) && k>=0
  return self if n == 1 || self == 0
  mag = abs**n**-1 ; theta = arg/n ; delta = 2*PI/n
  return rootn(mag,theta,delta,k>1 ? k-1:0) if kind_of?(Complex)
  return rootn(mag,theta,delta,k-1) if k>0 # kth root of n for any real
  return  mag.round(Roots.digits_to_show) if self > 0 # pos real default
  return -mag.round(Roots.digits_to_show) if n&1 == 1 # neg real default, n odd
  return rootn(mag,theta)    # neg real default, n even, 1st ccw root
end

#roots(n, opt = 0) ⇒ Object

return array of root n values, [] if no value



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/roots.rb', line 154

def roots(n,opt=0) #  return array of root n values, [] if no value
  raise "Root n not an integer > 0" unless n.kind_of?(Integer) && n>0
  raise "Invalid option" unless opt == 0 || opt =~ /^(c|e|i|o|r|C|E|I|O|R)/
  return [self] if n == 1 || self == 0
  mag = abs**n**-1 ; theta = arg/n ; delta = 2*PI/n
  roots = []
  case opt
  when /^(o|O)/  # odd  roots 1,3,5...
    0.step(n-1,2) {|k| roots << rootn(mag,theta,delta,k)}
  when /^(e|E)/  # even roots 2,4,6...
    1.step(n-1,2) {|k| roots << rootn(mag,theta,delta,k)}
  when /^(r|R)/  # real roots     Complex(x,0) = (x+i0)
    n.times {|k| x=rootn(mag,theta,delta,k); roots << x if x.imag == 0}
  when /^(i|I)/  # imaginry roots Complex(0,y) = (0+iy)
    n.times {|k| x=rootn(mag,theta,delta,k); roots << x if x.real == 0}
  when /^(c|C)/  # complex  roots Complex(x,y) = (x+iy)
    n.times {|k| x=rootn(mag,theta,delta,k); roots << x if x.arg*2 % PI != 0} 
  else           # all n roots
    n.times {|k| roots << rootn(mag,theta,delta,k)}
  end
  return roots
end