From: jzakiya Date: 2009-12-30T09:45:06+09:00 Subject: Re: Roots Module In looking for a nice home for my Roots module it seems mathn.rb is a good fit because it adds the functions sqrt|rsqrt to the Math module (do sqrt x, not x.sqrt). So I copied my roots.rb file into the same dir under lib which has mathn.rb, and add the follow code to mathn.rb at the top, under it's 'require' list: [Ruby 1.9.1p243] require 'roots' class Integer; include Roots end class Float; include Roots end class Rational include Roots def self.root(x); self.to_f.root end def self.roots(x); self.to_f.roots end end I had to do Rational like this because Rational(x/y).root(n) produced a NoMethodError, but Rational.to_f.root(n) takes care of that. I would like Complex(x,y).root(n) too, but I haven't figured out a nice way to do that yet, to match: sqrt Complex(x,y) though you can do: Complex(x,y)**n**-1 for all roots. It would be nice to have the simpler syntax, though. So now in irb if you load this in: >require 'mathn' >include Math # to also get functions sqrt|rsqrt So >sqrt -9 => (0+3i) >-9.root 2 => (0.0+3.0i) and >sqrt Rational(25/81) => (5/9) >Rational(25/81)**(1/2) => (5/9) >Rational(25/81)**2**-1 => (5/9) >Rational(25/81).root 2 => (5/9) # but >Rational(25/81)**0.5 => 0.55555555555556 along with Rational(x/y).roots(n,opt) Everything seems to work with only one known QUIRK. mathn.rb adds this to classes Fixnum and Bignum: class Fixnum|Bignum remove_method :/ alias / quo alias power! ** unless defined?(0.power!) def ** (other) if self < 0 && other.round != other Complex(self, 0.0) ** other else power!(other) end end end The line: alias power! ** unless defined?(0.power!) causes an error for Bignums, I get for (X).root(n) a NoMethodError: undefined method `power!' for (X):Bignum but not when I do a Fixnum (x).root(n). I can do (X).0.root[s](n) to get around this problem, and redefine these methods in Bignum like for Rationals, but that's a hack for a seemingly simple resolution. When I comment out the: # unless defined?(0.power!) in class Bignum the problem goes away. Also, if I don't load mathn.rb, and just load roots.rb and then mixin Roots in Integer and Float, as I did originally, I can do Bignums with no problems. Any ideas on what's the problem with Bignum class here? Thus, by doing this in mathn.rb, you get all the roots of real and rational numbers, and not just the sqrts.