/
big_float.cr
438 lines (360 loc) · 8.68 KB
/
big_float.cr
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
require "c/string"
require "big"
# A `BigFloat` can represent arbitrarily large floats.
#
# It is implemented under the hood with [GMP](https://gmplib.org/).
struct BigFloat < Float
include Comparable(Int)
include Comparable(BigFloat)
include Comparable(Float)
def initialize
LibGMP.mpf_init(out @mpf)
end
def initialize(str : String)
# Strip leading '+' char to smooth out cases with strings like "+123"
str = str.lchop('+')
# Strip '_' to make it compatible with int literals like "1_000_000"
str = str.delete('_')
if LibGMP.mpf_init_set_str(out @mpf, str, 10) == -1
raise ArgumentError.new("Invalid BigFloat: #{str.inspect}")
end
end
def initialize(num : BigInt)
LibGMP.mpf_init(out @mpf)
LibGMP.mpf_set_z(self, num)
end
def initialize(num : BigRational)
LibGMP.mpf_init(out @mpf)
LibGMP.mpf_set_q(self, num)
end
def initialize(num : BigFloat)
LibGMP.mpf_init(out @mpf)
LibGMP.mpf_set(self, num)
end
def initialize(num : Int8 | Int16 | Int32)
LibGMP.mpf_init_set_si(out @mpf, num)
end
def initialize(num : UInt8 | UInt16 | UInt32)
LibGMP.mpf_init_set_ui(out @mpf, num)
end
def initialize(num : Int64)
if LibGMP::Long == Int64
LibGMP.mpf_init_set_si(out @mpf, num)
else
LibGMP.mpf_init(out @mpf)
LibGMP.mpf_set_z(self, num.to_big_i)
end
end
def initialize(num : UInt64)
if LibGMP::ULong == UInt64
LibGMP.mpf_init_set_ui(out @mpf, num)
else
LibGMP.mpf_init(out @mpf)
LibGMP.mpf_set_z(self, num.to_big_i)
end
end
def initialize(num : Number)
LibGMP.mpf_init_set_d(out @mpf, num.to_f64)
end
def initialize(num : Float, precision : Int)
LibGMP.mpf_init2(out @mpf, precision.to_u64)
LibGMP.mpf_set_d(self, num.to_f64)
end
def initialize(@mpf : LibGMP::MPF)
end
def self.new
LibGMP.mpf_init(out mpf)
yield pointerof(mpf)
new(mpf)
end
# TODO: improve this
def_hash to_f64
def self.default_precision
LibGMP.mpf_get_default_prec
end
def self.default_precision=(prec : Int)
LibGMP.mpf_set_default_prec(prec.to_u64)
end
def <=>(other : BigFloat)
LibGMP.mpf_cmp(self, other)
end
def <=>(other : BigInt)
LibGMP.mpf_cmp_z(self, other)
end
def <=>(other : Float32 | Float64)
LibGMP.mpf_cmp_d(self, other.to_f64)
end
def <=>(other : Number)
if other.is_a?(Int8 | Int16 | Int32) || (LibGMP::Long == Int64 && other.is_a?(Int64))
LibGMP.mpf_cmp_si(self, other)
elsif other.is_a?(UInt8 | UInt16 | UInt32) || (LibGMP::ULong == UInt64 && other.is_a?(UInt64))
LibGMP.mpf_cmp_ui(self, other)
else
LibGMP.mpf_cmp(self, other.to_big_f)
end
end
def - : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_neg(mpf, self) }
end
def +(other : Number) : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_add(mpf, self, other.to_big_f) }
end
def -(other : Number) : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_sub(mpf, self, other.to_big_f) }
end
def *(other : Number) : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_mul(mpf, self, other.to_big_f) }
end
def /(other : BigFloat) : BigFloat
# Division by 0 in BigFloat is not allowed, there is no BigFloat::Infinity
raise DivisionByZeroError.new if other == 0
BigFloat.new { |mpf| LibGMP.mpf_div(mpf, self, other) }
end
Number.expand_div [BigInt], BigFloat
Number.expand_div [BigDecimal], BigDecimal
Number.expand_div [BigRational], BigRational
def **(other : Int) : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_pow_ui(mpf, self, other.to_u64) }
end
def abs : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_abs(mpf, self) }
end
def ceil : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_ceil(mpf, self) }
end
def floor : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_floor(mpf, self) }
end
def trunc : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_trunc(mpf, self) }
end
def to_f64 : Float64
LibGMP.mpf_get_d(self)
end
def to_f32 : Float32
to_f64.to_f32
end
def to_f : Float64
to_f64
end
def to_f32! : Float32
to_f64.to_f32!
end
def to_f64! : Float64
to_f64
end
def to_f! : Float64
to_f64!
end
def to_big_f : BigFloat
self
end
def to_big_i : BigInt
BigInt.new { |mpz| LibGMP.set_f(mpz, mpf) }
end
def to_i64 : Int64
raise OverflowError.new unless LibGMP::Long::MIN <= self <= LibGMP::Long::MAX
LibGMP.mpf_get_si(self).to_i64!
end
def to_i32 : Int32
to_i64.to_i32
end
def to_i16 : Int16
to_i64.to_i16
end
def to_i8 : Int8
to_i64.to_i8
end
def to_i : Int32
to_i32
end
def to_i! : Int32
to_i32!
end
def to_i8! : Int8
LibGMP.mpf_get_si(self).to_i8!
end
def to_i16! : Int16
LibGMP.mpf_get_si(self).to_i16!
end
def to_i32! : Int32
LibGMP.mpf_get_si(self).to_i32!
end
def to_i64! : Int64
LibGMP.mpf_get_si(self).to_i64!
end
def to_u64 : UInt64
raise OverflowError.new unless 0 <= self <= LibGMP::ULong::MAX
LibGMP.mpf_get_ui(self).to_u64!
end
def to_u32 : UInt32
to_u64.to_u32
end
def to_u16 : UInt16
to_u64.to_u16
end
def to_u8 : UInt8
to_u64.to_u8
end
def to_u : UInt32
to_u32
end
def to_u! : UInt32
to_u32!
end
def to_u8! : UInt8
LibGMP.mpf_get_ui(self).to_u8!
end
def to_u16! : UInt16
LibGMP.mpf_get_ui(self).to_u16!
end
def to_u32! : UInt32
LibGMP.mpf_get_ui(self).to_u32!
end
def to_u64! : UInt64
LibGMP.mpf_get_ui(self).to_u64!
end
def to_unsafe
mpf
end
def to_s(io : IO) : Nil
cstr = LibGMP.mpf_get_str(nil, out expptr, 10, 0, self)
length = LibC.strlen(cstr)
decimal_set = false
io << '-' if self < 0
if expptr == 0
io << 0
elsif expptr < 0
io << 0 << '.'
decimal_set = true
expptr.abs.times { io << 0 }
end
expptr += 1 if self < 0
length.times do |i|
next if cstr[i] == 45 # '-'
if i == expptr
io << '.'
decimal_set = true
end
io << cstr[i].unsafe_chr
end
(expptr - length).times { io << 0 } if expptr > 0
if !decimal_set
io << ".0"
end
end
def clone
self
end
# Rounds towards the nearest integer. If both neighboring integers are equidistant,
# rounds towards the even neighbor (Banker's rounding).
def round_even : self
if self >= 0
halfway = self + 0.5
else
halfway = self - 0.5
end
if halfway.integer?
if halfway == (halfway / 2).trunc * 2
halfway
else
halfway - sign
end
else
if self >= 0
halfway.floor
else
halfway.ceil
end
end
end
# Rounds towards the nearest integer. If both neighboring integers are equidistant,
# rounds away from zero.
def round_away : self
if self >= 0
(self + 0.5).floor
else
(self - 0.5).ceil
end
end
protected def integer?
!LibGMP.mpf_integer_p(mpf).zero?
end
private def mpf
pointerof(@mpf)
end
end
struct Number
include Comparable(BigFloat)
def <=>(other : BigFloat)
-(other <=> self)
end
def +(other : BigFloat)
other + self
end
def -(other : BigFloat)
to_big_f - other
end
def *(other : BigFloat) : BigFloat
other * self
end
def /(other : BigFloat) : BigFloat
to_big_f / other
end
def to_big_f : BigFloat
BigFloat.new(self)
end
end
class String
# Converts `self` to a `BigFloat`.
#
# ```
# require "big"
# "1234.0".to_big_f
# ```
def to_big_f : BigFloat
BigFloat.new(self)
end
end
module Math
# Decomposes the given floating-point *value* into a normalized fraction and an integral power of two.
def frexp(value : BigFloat) : {BigFloat, Int64}
LibGMP.mpf_get_d_2exp(out exp, value) # we need BigFloat frac, so will skip Float64 one.
frac = BigFloat.new do |mpf|
if exp >= 0
LibGMP.mpf_div_2exp(mpf, value, exp)
else
LibGMP.mpf_mul_2exp(mpf, value, -exp)
end
end
{frac, exp.to_i64}
end
# Calculates the square root of *value*.
#
# ```
# require "big"
#
# Math.sqrt(1_000_000_000_000.to_big_f * 1_000_000_000_000.to_big_f) # => 1000000000000.0
# ```
def sqrt(value : BigFloat) : BigFloat
BigFloat.new { |mpf| LibGMP.mpf_sqrt(mpf, value) }
end
end
# :nodoc:
struct Crystal::Hasher
def float(value : BigFloat)
normalized_hash = float_normalize_wrap(value) do |value|
# more exact version of `Math.frexp`
LibGMP.mpf_get_d_2exp(out exp, value)
frac = BigFloat.new do |mpf|
if exp >= 0
LibGMP.mpf_div_2exp(mpf, value, exp)
else
LibGMP.mpf_mul_2exp(mpf, value, -exp)
end
end
float_normalize_reference(value, frac, exp)
end
permute(normalized_hash)
end
end