module Roots

file roots.rb

Public Class Methods

digits_to_show(n = @digits_to_show || 8) click to toggle source
# File lib/roots.rb, line 181
def self.digits_to_show(n = @digits_to_show || 8)
  @digits_to_show = n < 1 ? 1 : n 
end

Public Instance Methods

cosine(x) click to toggle source
# File lib/roots.rb, line 180
def cosine(x); sin(x).abs == 1 ? 0 : cos(x) end
root(n,k=0) click to toggle source
# 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
rootn(mag,theta,delta=0,k=0) click to toggle source
# File lib/roots.rb, line 185
def rootn(mag,theta,delta=0,k=0) # root k of n of real|complex
  angle_n = theta + k*delta
  x = mag*Complex(cosine(angle_n),sine(angle_n))
  Complex(x.real.round(Roots.digits_to_show), x.imag.round(Roots.digits_to_show))
end
roots(n,opt=0) click to toggle source
# 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

Private Instance Methods

sine(x) click to toggle source
# File lib/roots.rb, line 179
def sine(x);   cos(x).abs == 1 ? 0 : sin(x) end