Module: Units::Math

Included in:
System
Defined in:
lib/units/system.rb,
lib/units/math.rb

Overview

mathematical functions available to unit blocks are defined here

Class Method Summary collapse

Class Method Details

.atan2(x, y) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/units/math.rb', line 27

def atan2(x,y)
  if x.kind_of?(Measure)
    if y.kind_of?(Measure)
      if x.base.to_si.units != y.base.to_si.units
        raise ArgumentError,"Inconsistent units for atan2 arguments #{x.u}, #{y.u}"
      end
      # or x = x.to_si.magnitude, y=y.to_si.magnitude
      y = y.in(x.units)
      x = x.magnitude
    else
      raise ArgumentError,"Invalid dimensions for atan2 argument #{x.u}" unless x.dimensionless?
      x = x.magnitude
    end
  elsif y.kind_of?(Measure)
    raise ArgumentError,"Invalid dimensions for atan2 argument #{y.u}" unless y.dimensionless?
    y = y.magnitude
  end
  Units.u{::Math.atan2(x,y)*rad}
end

.sqrt(x) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/units/math.rb', line 47

def sqrt(x)
  if x.kind_of?(Measure)
    if x.units.empty?
      Measure[::Math.sqrt(x.magnitude)]
    else
      y = x
      all_even = x.units.values.map{|v| v.last % 2}.uniq == [0]
      unless all_even
        x = x.base
        all_even = x.units.values.map{|v| v.last % 2}.uniq == [0]
      end
      if all_even
        units = {}
        x.units.each do |dim, (unit, exp)|
          units[dim] = [unit, exp/2]
        end
        Measure[::Math.sqrt(x.magnitude), units]
      else
        raise ArgumentError, "Invalid dimensiones for sqrt argument #{y}"
      end
    end
  else
    ::Math.sqrt(x)
  end
end