-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathradex.rb
More file actions
165 lines (139 loc) · 2.85 KB
/
radex.rb
File metadata and controls
165 lines (139 loc) · 2.85 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
load File.join(File.dirname(__FILE__), 'numex.rb')
class Integer
def sqrt
Radex[0, 1, self]
end
end
class Rational
def sqrt
Radex[0, 1, self]
end
end
# a + b * sqrt(c) where a, b, c = Rational
class Radex < Numeric
include Numex
attr :a, :b, :c
def initialize(a, b, c)
@a = a
@b = b
@c = c
end
class << self
def [](a, b, c)
if b == 0 || c == 0
a
else
x, c = c.factor_out_powers_of(2)
if c == 1
a + b*x
else
new(a, b*x, c)
end
end
end
end
def create(a, b)
if b == 0
a
else
self.class.new(a, b, c)
end
end
def inspect
babs = b.abs
"#{a unless a == 0}#{b < 0 ? '-' : ('+' unless a == 0)}#{babs unless babs == 1}√#{c}"
end
def to_s
inspect
end
def to_f
sqrt(c.to_f) * b.to_f + a.to_f
end
def is_radex?(x)
if x.is_a? Radex
unless self.c == x.c
raise "Cannot combine mismatched radicals #{self.c} and #{x.c}"
end
true
end
end
def ==(x)
x.is_a?(Radex) && a == x.a && b == x.b && c == x.c
end
def positive?
if a == 0 || a*a < b*b*c
b > 0
else
a > 0
end
end
def <=>(x)
if is_radex?(x)
da = a - x.a
db = b - x.b
else
da = a - x
db = b
end
if da == 0 || da*da < db*db*c
db <=> 0
else
da <=> 0
end
end
def sum(x, d=1)
if is_radex?(x)
create(a + d*x.a, b + d*x.b)
else
create(a + d*x, b)
end
end
def +(x)
sum(x, 1)
end
def -(x)
sum(x, -1)
end
def -@
create(-a, -b)
end
def *(x)
if is_radex?(x)
create(a*x.a + b*x.b*c, a*x.b + b*x.a)
else
create(a*x, b*x)
end
end
def reciprocal_denominator
a*a - b*b*c
end
def reciprocal
# 1 a - b_c
# ------- = ----------
# a + b_c a^2 - cb^2
d = reciprocal_denominator
create(a/d, -b/d)
end
def /(x)
if is_radex?(x)
d = reciprocal_denominator
create((a*x.a - b*x.b*c)/d, (b*x.a - a*x.b)/d)
else
create(a/x, b/x)
end
end
def **(x)
unless x.denominator == 1
raise "Can't raise radical to fractional exponent"
end
if x < 0
reciprocal**(-x)
elsif x == 0
1
elsif x == 1
self
else
self * self**(x-1)
end
end
end