Method: RubyUnits::Unit#root
- Defined in:
- lib/ruby_units/unit.rb
#root(n) ⇒ Unit
Calculates the n-th root of a unit if n < 0, returns 1/unit^(1/n)
900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 |
# File 'lib/ruby_units/unit.rb', line 900 def root(n) raise ArgumentError, "Cannot take the root of a temperature" if self.is_temperature? raise ArgumentError, "Exponent must an Integer" unless n.kind_of?(Integer) raise ArgumentError, "0th root undefined" if n.zero? return self if n == 1 return self.root(n.abs).inverse if n < 0 vec = self.unit_signature_vector vec =vec.map { |x| x % n } raise ArgumentError, "Illegal root" unless vec.max == 0 num = @numerator.dup den = @denominator.dup for item in @numerator.uniq do x = num.find_all { |i| i==item }.size r = ((x/n)*(n-1)).to_int r.times { |y| num.delete_at(num.index(item)) } end for item in @denominator.uniq do x = den.find_all { |i| i==item }.size r = ((x/n)*(n-1)).to_int r.times { |y| den.delete_at(den.index(item)) } end q = @scalar < 0 ? (-1)**Rational(1, n) * (@scalar.abs)**Rational(1, n) : @scalar**Rational(1, n) return RubyUnits::Unit.new(:scalar => q, :numerator => num, :denominator => den) end |