lib/numru/gphys/unumeric.rb in gphys-1.2.2.1 vs lib/numru/gphys/unumeric.rb in gphys-1.4.3
- old
+ new
@@ -181,10 +181,54 @@
uni = Units.new(uni) if String === uni
raise TypeError unless Units === uni
@val, @uni = val, uni
end
+ ##########################
+ # Tentative class to assist basic arithmetic operations between
+ # quantities without (like Numeric) and with (like UNumeric) units.
+ #
+ # The fundamental problem here is that the desired unit conversion
+ # to convert the Numeric is different between additional methods (+,-)
+ # and multiplicative methods (*,/). In the former, the
+ # numeric should be converted to have the same units with
+ # the other operand, and in the latter, it should be
+ # non-dimensional.
+ #
+ class Num2Coerce
+ # * num (Numeric, NArray etc -- numeric-like object without units).
+ # It must be KNOWN by the other operand.
+ def initialize(num)
+ @num = num
+ end
+
+ def num; @num; end
+
+ def +(o); o + num; end
+ def -(o); (-o) + num; end
+ def *(o); o * num; end
+ def /(o); o**(-1) * num;end
+
+ def >(o); o<num; end
+ def <(o); o>num; end
+ def >=(o); o<=num; end
+ def <=(o); o>=num; end
+ def ==(o); o==num; end
+ def ===(o); o===num; end
+
+ def <=>(o); c = o<=>num or -c; end
+
+ ['%','**','divmod'].each do |op|
+ eval <<-EOS
+ def #{op}(o)
+ raise("operation #{op} is unavailable between Numeric and "+o.class.to_s)
+ end
+ EOS
+ end
+ end
+ ##########################
+
def self::[](val, uni)
new(val, uni)
end
@@supported_calendars = [nil,"gregorian", "standard", "proleptic_gregorian",
@@ -366,15 +410,15 @@
end
def coerce(other)
case
when Numeric
- c_other = UNumeric.new( other, Units.new("1") )
- when Array
- c_other = VArray.new( NArray.to_na(other) )
- when NArray
- c_other = VArray.new( other )
+ c_other = Num2Coerce.new( other )
+ #when Array
+ # c_other = VArray.new( NArray.to_na(other) )
+ #when NArray
+ # c_other = VArray.new( other )
else
raise "#{self.class}: cannot coerce #{other.class}"
end
[ c_other, self ]
end
@@ -516,9 +560,10 @@
p a+c
p a+7
p a*7
p -a
p a-b, a-1000, a/100
+ p 1 + a
p a.log, a.sin
p UNumeric[1.0,Units['1']].atan2( UNumeric[1.0,Units['1']] )
print "\n** Section 2 **\n"
p a > 1