-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrootex.rb
More file actions
129 lines (109 loc) · 2.8 KB
/
rootex.rb
File metadata and controls
129 lines (109 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
load File.join(File.dirname(__FILE__), 'math.rb')
class Rootex < Numeric
# [prime_roots] => coefficient
attr :terms
def initialize(terms)
@terms = terms
unless @terms.frozen?
@terms.default = 0
@terms.freeze
end
end
class << self
def [](terms={})
h = {}
h.default = 0
terms.each do |root, co|
prime_roots = []
root.prime_factors.each do |prime, exponent|
q, r = exponent.divmod(2)
co *= prime**q
prime_roots << prime if r == 1
end
h[prime_roots.sort] += co
end
simplify(h)
end
def simplify(terms)
terms.delete_if{|_, co| co == 0}
if terms.keys.all?(&:empty?)
terms[[]]
else
new(Hash[terms.sort_by{|roots, _| roots.reduce(1, &:*)}])
end
end
end
def inspect
terms.reduce('') do |s, (roots, co)|
if s.empty?
s << '-' if co < 0
else
s << (co < 0 ? ' -' : ' +')
end
unless co.abs == 1
s << co.abs.to_s
end
unless roots.empty?
s << "√#{roots.reduce(1, &:*)}"
end
s
end
end
def to_f
terms.reduce(0.0) do |f, (roots, co)|
f + (co * sqrt(roots.reduce(1, &:*)))
end
end
def sum(d, x)
if x == 0
self
else
h = {}
h.default = 0
terms.each do |roots, co|
h[roots] += co
end
if x.is_a? Rootex
x.terms.each do |roots, co|
h[roots] += d*co
end
else
h[[]] += d*x
end
self.class.simplify(h)
end
end
def +(x)
sum(1, x)
end
def -(x)
sum(-1, x)
end
def -@
self.class.new(Hash[terms.map{|roots, co| [roots, -co] }])
end
def *(x)
if x == 0
0
elsif x == 1
self
else
h = {}
h.default = 0
if x.is_a? Rootex
terms.each do |aroots, aco|
x.terms.each do |broots, bco|
squares = aroots & broots
roots = ((aroots | broots) - squares).sort
h[roots] += aco * bco * squares.reduce(1, &:*)
end
end
else
terms.each do |roots, co|
h[roots] += co * x
end
end
self.class.simplify(h)
end
end
end