Class: MathViz::Unit

Inherits:
Object show all
Defined in:
lib/mathviz.rb

Overview

Value objects that do the actual unit tracking.

Contains all the interesting power tracking and cancellation.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(h = nil) ⇒ Unit

  • With a symbol, creates a simple unit.

  • With a hash-of-powers, it simply copies those values.

  • Otherwise, it becomes a dimensionless unit.



58
59
60
61
62
63
64
65
66
# File 'lib/mathviz.rb', line 58

def initialize(h = nil)
  @unit = Hash.new(0)
  case h
  when Hash; @unit.merge!(h); normalize!
  when Symbol; @unit[h] = 1
  end
  @unit.freeze
  freeze
end

Instance Attribute Details

#unitObject (readonly)

The interal representation. Current implementation method is hash-of-powers; e.g. => 2, :s => -1 represents m*m/s



53
54
55
# File 'lib/mathviz.rb', line 53

def unit
  @unit
end

Instance Method Details

#*(other) ⇒ Object



87
88
89
90
91
92
93
# File 'lib/mathviz.rb', line 87

def *(other)
  x = @unit.dup
  other.unit.each do |u,power|
    x[u] += power
  end
  MathViz::Unit.new(x)
end

#/(other) ⇒ Object



95
96
97
98
99
100
101
# File 'lib/mathviz.rb', line 95

def /(other)
  x = @unit.dup
  other.unit.each do |u,power|
    x[u] -= power
  end
  MathViz::Unit.new(x)
end

#binop(other) ⇒ Object Also known as: +, -, <, >, ==, max, min, &, |

Implement a simple binary operation. It verifies that the units match and returns the unit ERROR if not.



69
70
71
72
73
74
75
# File 'lib/mathviz.rb', line 69

def binop(other)
  if (unit != other.unit)
    #p "#{to_s} !+- #{other.to_s}"
    return MathViz::Unit.new(:ERROR)
  end
  return self
end

#denominatorObject



107
108
109
# File 'lib/mathviz.rb', line 107

def denominator
  unit.reject {|u,power| power > 0}
end

#numeratorObject



103
104
105
# File 'lib/mathviz.rb', line 103

def numerator
  unit.reject {|u,power| power < 0}
end

#to_sObject



111
112
113
114
115
116
117
# File 'lib/mathviz.rb', line 111

def to_s
  n = stream(numerator)
  d = stream(denominator)
  return '' unless (n || d)
  return "#{n||1}/#{d}" if d
  return n
end