Class: Symbolic::Summand
- Inherits:
-
Object
show all
- Includes:
- Symbolic
- Defined in:
- lib/symbolic/summand.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Methods included from Symbolic
#*, #**, #+, #+@, #-, #-@, #/, #coerce, #operations, #undefined_variables
Constructor Details
#initialize(summands) ⇒ Summand
Returns a new instance of Summand.
48
49
50
|
# File 'lib/symbolic/summand.rb', line 48
def initialize(summands)
@summands = summands
end
|
Class Method Details
.add(var1, var2) ⇒ Object
5
6
7
8
|
# File 'lib/symbolic/summand.rb', line 5
def add(var1, var2)
simplify_coefficients! summands = unite(summands(var1), summands(var2))
simplify(*summands) || new(summands)
end
|
.reverse(var) ⇒ Object
15
16
17
18
19
20
|
# File 'lib/symbolic/summand.rb', line 15
def reverse(var)
summands(var).tap do |it|
it[0] = -it[0]
it[1] = Hash[*it[1].map {|b,e| [b,-e] }.flatten]
end
end
|
.simplify(numeric, symbolic) ⇒ Object
39
40
41
42
43
44
45
|
# File 'lib/symbolic/summand.rb', line 39
def simplify(numeric, symbolic)
if symbolic.empty?
numeric
elsif numeric == 0 && symbolic.size == 1
symbolic.values.first * symbolic.keys.first
end
end
|
.simplify_coefficients!(summands) ⇒ Object
35
36
37
|
# File 'lib/symbolic/summand.rb', line 35
def simplify_coefficients!(summands)
summands[1].delete_if {|base, coef| coef == 0 }
end
|
.subtract(var1, var2) ⇒ Object
10
11
12
13
|
# File 'lib/symbolic/summand.rb', line 10
def subtract(var1, var2)
simplify_coefficients! summands = unite(summands(var1), reverse(var2))
simplify(*summands) || new(summands)
end
|
.summands(var) ⇒ Object
22
23
24
|
# File 'lib/symbolic/summand.rb', line 22
def summands(var)
var.is_a?(Symbolic) ? var.send(:summands) : [var, {}]
end
|
.unite(summands1, summands2) ⇒ Object
26
27
28
29
30
31
32
33
|
# File 'lib/symbolic/summand.rb', line 26
def unite(summands1, summands2)
numeric1, symbolic1 = summands1
numeric2, symbolic2 = summands2
numeric = numeric1 + numeric2
symbolic = symbolic1.merge(symbolic2) {|base, coef1, coef2| coef1 + coef2 }
return numeric, symbolic
end
|
Instance Method Details
#==(object) ⇒ Object
60
61
62
|
# File 'lib/symbolic/summand.rb', line 60
def ==(object)
object.send(:summands) == @summands rescue false
end
|
#to_s ⇒ Object
64
65
66
67
68
69
|
# File 'lib/symbolic/summand.rb', line 64
def to_s
output = @summands[1].map {|base, coef| coef_to_string(coef) + base.to_s }
output << remainder_to_string(@summands[0]) if @summands[0] != 0
output[0] = output.first[1..-1]
output.join
end
|
#value ⇒ Object
52
53
54
|
# File 'lib/symbolic/summand.rb', line 52
def value
@summands[1].inject(@summands[0]) {|value, (base, coef)| value + base.value * coef.value }
end
|
#variables ⇒ Object
56
57
58
|
# File 'lib/symbolic/summand.rb', line 56
def variables
@summands[1].map {|k,v| [variables_of(k), variables_of(v)] }.flatten.uniq
end
|