-
Notifications
You must be signed in to change notification settings - Fork 11
/
decimal64.go
575 lines (517 loc) · 13.3 KB
/
decimal64.go
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package decimal
import (
"fmt"
"math"
"math/bits"
"strconv"
)
type discardedDigit int
const (
eq0 discardedDigit = 1 << iota
lt5
eq5
gt5
)
type flavor int8
const (
flInf flavor = 0
flNormal53 flavor = 1 << (iota - 1)
flNormal51
flQNaN
flSNaN
flNormal = flNormal53 | flNormal51
flNaN = flQNaN | flSNaN
)
func (f flavor) normal() bool {
return f&flNormal != 0
}
func (f flavor) nan() bool {
return f&flNaN != 0
}
func (f flavor) String() string {
switch f {
case flInf:
return "Infinity"
case flNormal53:
return "Normal53"
case flNormal51:
return "Normal51"
case flQNaN:
return "QNaN"
case flSNaN:
return "SNaN"
default:
return fmt.Sprintf("Unknown flavor %d", f)
}
}
// Rounding defines how arithmetic operations round numbers in certain operations.
type Rounding int8
const (
// HalfUp rounds to the nearest number, rounding away from zero if the
// number is exactly halfway between two possible roundings.
HalfUp Rounding = iota
// HalfEven rounds to the nearest number, rounding to the nearest even
// number if the number is exactly halfway between two possible roundings.
HalfEven
// Down rounds towards zero.
Down
)
func (r Rounding) String() string {
switch r {
case HalfUp:
return "HalfUp"
case HalfEven:
return "HalfEven"
case Down:
return "Down"
default:
return fmt.Sprintf("Unknown rounding mode %d", r)
}
}
// Context64 may be used to tune the behaviour of arithmetic operations.
type Context64 struct {
// Rounding sets the rounding behaviour of arithmetic operations.
Rounding Rounding
// TODO: implement
// // Signal causes arithmetic operations to panic when encountering a sNaN.
// Signal bool
}
var tenToThe = [32]uint64{ // pad for efficient indexing
1,
10,
100,
1000,
10000,
100000,
1000000,
10000000,
100000000,
1000000000,
10000000000,
100000000000,
1000000000000,
10000000000000,
100000000000000,
1000000000000000,
10000000000000000,
100000000000000000,
1000000000000000000,
10000000000000000000,
}
func (ctx Rounding) round(significand uint64, rndStatus discardedDigit) uint64 {
switch ctx {
case HalfUp:
if rndStatus&(gt5|eq5) != 0 {
return significand + 1
}
case HalfEven:
if (rndStatus == eq5 && significand%2 == 1) || rndStatus == gt5 {
return significand + 1
}
case Down: // TODO: implement proper down behaviour
return significand
// case roundFloor:// TODO: implement proper Floor behaviour
// return significand
// case roundCeiling: //TODO: fine tune ceiling,
}
return significand
}
var ErrNaN64 error = Error("sNaN64")
var small64s = []Decimal64{
new64str(newFromPartsRaw(1, -14, 1*decimal64Base).bits, "-10"),
new64str(newFromPartsRaw(1, -15, 9*decimal64Base).bits, "-9"),
new64str(newFromPartsRaw(1, -15, 8*decimal64Base).bits, "-8"),
new64str(newFromPartsRaw(1, -15, 7*decimal64Base).bits, "-7"),
new64str(newFromPartsRaw(1, -15, 6*decimal64Base).bits, "-6"),
new64str(newFromPartsRaw(1, -15, 5*decimal64Base).bits, "-5"),
new64str(newFromPartsRaw(1, -15, 4*decimal64Base).bits, "-4"),
new64str(newFromPartsRaw(1, -15, 3*decimal64Base).bits, "-3"),
new64str(newFromPartsRaw(1, -15, 2*decimal64Base).bits, "-2"),
new64str(newFromPartsRaw(1, -15, 1*decimal64Base).bits, "-1"),
// TODO: Decimal64{}?
new64str(newFromPartsRaw(0, 0, 0).bits, "0"),
new64str(newFromPartsRaw(0, -15, 1*decimal64Base).bits, "1"),
new64str(newFromPartsRaw(0, -15, 2*decimal64Base).bits, "2"),
new64str(newFromPartsRaw(0, -15, 3*decimal64Base).bits, "3"),
new64str(newFromPartsRaw(0, -15, 4*decimal64Base).bits, "4"),
new64str(newFromPartsRaw(0, -15, 5*decimal64Base).bits, "5"),
new64str(newFromPartsRaw(0, -15, 6*decimal64Base).bits, "6"),
new64str(newFromPartsRaw(0, -15, 7*decimal64Base).bits, "7"),
new64str(newFromPartsRaw(0, -15, 8*decimal64Base).bits, "8"),
new64str(newFromPartsRaw(0, -15, 9*decimal64Base).bits, "9"),
new64str(newFromPartsRaw(0, -14, 1*decimal64Base).bits, "10"),
}
var small64Strings = func() map[uint64]string {
m := make(map[uint64]string, len(small64s))
for i := -10; i <= 10; i++ {
m[small64s[10+i].bits] = strconv.Itoa(i)
}
return m
}()
// New64FromInt64 returns a new Decimal64 with the given value.
func New64FromInt64(i int64) Decimal64 {
if i >= -10 && i <= 10 {
return small64s[10+i]
}
return new64FromInt64(i)
}
func new64FromInt64(value int64) Decimal64 {
sign := int8(0)
if value < 0 {
sign = 1
value = -value
}
// TODO: handle abs(value) > 9 999 999 999 999 999
// lz := bits.LeadingZeros64(uint64(value))
exp, significand := renormalize(0, uint64(value))
checkSignificandIsNormal(significand)
return newFromParts(sign, exp, significand)
}
func renormalize(exp int16, significand uint64) (int16, uint64) {
numDigits := int16(bits.Len64(significand) * 3 / 10)
normExp := 15 - numDigits
if normExp > 0 {
if normExp > exp+expOffset {
normExp = exp + expOffset
}
exp -= normExp
significand *= tenToThe[normExp]
} else if normExp < -1 {
normExp++
if normExp < exp-expMax {
normExp = exp - expMax
}
exp -= normExp
significand /= tenToThe[-normExp]
}
switch {
case significand < decimal64Base && exp > -expOffset:
return exp - 1, significand * 10
case significand >= 10*decimal64Base:
return exp + 1, significand / 10
default:
return exp, significand
}
}
// roundStatus gives info about the truncated part of the significand that can't be fully stored in 16 decimal digits.
func roundStatus(significand uint64, expDiff int16) discardedDigit {
if expDiff > 19 && significand != 0 {
return lt5
}
remainder := significand % tenToThe[expDiff]
midpoint := 5 * tenToThe[expDiff-1]
if remainder == 0 {
return eq0
} else if remainder < midpoint {
return lt5
} else if remainder == midpoint {
return eq5
}
return gt5
}
func newFromParts(sign int8, exp int16, significand uint64) Decimal64 {
return new64(newFromPartsRaw(sign, exp, significand).bits)
}
func newFromPartsRaw(sign int8, exp int16, significand uint64) Decimal64 {
s := uint64(sign) << 63
if significand < 0x8<<50 {
// s EEeeeeeeee (0)ttt tttttttttt tttttttttt tttttttttt tttttttttt tttttttttt
// EE ∈ {00, 01, 10}
return Decimal64{bits: s | uint64(exp+expOffset)<<(63-10) | significand}
}
// s 11EEeeeeeeee (100)t tttttttttt tttttttttt tttttttttt tttttttttt tttttttttt
// EE ∈ {00, 01, 10}
significand &= 0x8<<50 - 1
return Decimal64{bits: s | uint64(0xc00|(exp+expOffset))<<(63-12) | significand}
}
func (d Decimal64) parts() (fl flavor, sign int8, exp int16, significand uint64) {
sign = int8(d.bits >> 63)
switch (d.bits >> (63 - 4)) & 0xf {
case 15:
switch (d.bits >> (63 - 6)) & 3 {
case 0, 1:
fl = flInf
case 2:
fl = flQNaN
significand = d.bits & (1<<51 - 1)
return
case 3:
fl = flSNaN
significand = d.bits & (1<<51 - 1)
return
}
case 12, 13, 14:
// s 11EEeeeeeeee (100)t tttttttttt tttttttttt tttttttttt tttttttttt tttttttttt
// EE ∈ {00, 01, 10}
fl = flNormal51
exp = int16((d.bits>>(63-12))&(1<<10-1)) - expOffset
significand = d.bits&(1<<51-1) | (1 << 53)
default:
// s EEeeeeeeee (0)ttt tttttttttt tttttttttt tttttttttt tttttttttt tttttttttt
// EE ∈ {00, 01, 10}
fl = flNormal53
exp = int16((d.bits>>(63-10))&(1<<10-1)) - expOffset
significand = d.bits & (1<<53 - 1)
if significand == 0 {
exp = 0
}
}
return
}
func expWholeFrac(exp int16, significand uint64) (exp2 int16, whole uint64, frac uint64) {
if significand == 0 {
return 0, 0, 0
}
if exp >= 0 {
return exp, significand, 0
}
n := uint128T{significand, 0}
exp += 16
if exp > 0 {
n.mul64(&n, tenToThe[exp])
exp = 0
} else {
// exp++ till it hits 0 or continuing would throw away digits.
for step := 3; step >= 0; step-- {
expStep := int16(1) << step
powerOf10 := tenToThe[expStep]
for ; n.lo >= powerOf10 && exp <= -expStep; exp += expStep {
quo := n.lo / powerOf10
rem := n.lo - quo*powerOf10
if rem > 0 {
break
}
n.lo = quo
}
}
}
var whole128 uint128T
whole128.div10base(&n)
var x uint128T
x.mul64(&whole128, 10*decimal64Base)
var frac128 uint128T
frac128.sub(&n, &x)
return exp, whole128.lo, frac128.lo
}
// Float64 returns a float64 representation of d.
func (d Decimal64) Float64() float64 {
fl, sign, exp, significand := d.parts()
switch fl {
case flNormal53, flNormal51:
if significand == 0 {
return 0.0 * float64(1-2*sign)
}
if exp&1 == 1 {
exp--
significand *= 10
}
return float64(1-2*sign) * float64(significand) * math.Pow10(int(exp))
case flInf:
return math.Inf(1 - 2*int(sign))
case flQNaN:
return math.NaN()
}
panic(ErrNaN64)
}
// Int64 returns an int64 representation of d, clamped to [[math.MinInt64], [math.MaxInt64]].
func (d Decimal64) Int64() int64 {
i, _ := d.Int64x()
return i
}
// Int64 returns an int64 representation of d, clamped to [[math.MinInt64],
// [math.MaxInt64]].
// The second return value, exact indicates whether New64FromInt64(i) == d.
func (d Decimal64) Int64x() (i int64, exact bool) {
fl, sign, exp, significand := d.parts()
switch fl {
case flInf:
if sign == 0 {
return math.MaxInt64, false
}
return math.MinInt64, false
case flQNaN:
return 0, false
case flSNaN:
panic(ErrNaN64)
}
exp, whole, frac := expWholeFrac(exp, significand)
for exp > 0 && whole < math.MaxInt64/10 {
exp--
whole *= 10
}
if exp > 0 {
return math.MaxInt64, false
}
return int64(1-2*sign) * int64(whole), frac == 0
}
// IsZero returns true if the Decimal encodes a zero value.
func (d Decimal64) IsZero() bool {
fl, _, _, significand := d.parts()
return significand == 0 && fl.normal()
}
// IsInf indicates whether d is ±∞.
func (d Decimal64) IsInf() bool {
return d.flavor() == flInf
}
// IsNaN indicates whether d is not a number.
func (d Decimal64) IsNaN() bool {
return d.flavor().nan()
}
// IsQNaN indicates whether d is a quiet NaN.
func (d Decimal64) IsQNaN() bool {
return d.flavor() == flQNaN
}
// IsSNaN indicates whether d is a signalling NaN.
func (d Decimal64) IsSNaN() bool {
return d.flavor() == flSNaN
}
// IsInt indicates whether d is an integer.
func (d Decimal64) IsInt() bool {
fl, _, exp, significand := d.parts()
switch fl {
case flNormal53, flNormal51:
_, _, frac := expWholeFrac(exp, significand)
return frac == 0
default:
return false
}
}
// quiet returns a quiet form of d, which must be a NaN.
func (d Decimal64) quiet() Decimal64 {
return new64(d.bits &^ (2 << 56))
}
// IsSubnormal indicates whether d is a subnormal.
func (d Decimal64) IsSubnormal() bool {
fl, _, _, significand := d.parts()
return significand != 0 && significand < decimal64Base && fl.normal()
}
// Sign returns -1/0/1 if d is </=/> 0, respectively.
func (d Decimal64) Sign() int {
if d == Zero64 || d == NegZero64 {
return 0
}
return 1 - 2*int(d.bits>>63)
}
// Signbit indicates whether d is negative or -0.
func (d Decimal64) Signbit() bool {
return d.bits>>63 == 1
}
func (d Decimal64) ScaleB(e Decimal64) Decimal64 {
var dp, ep decParts
if nan, is := checkNan(d, e, &dp, &ep); is {
return nan
}
if !dp.fl.normal() || dp.isZero() {
return d
}
if !ep.fl.normal() {
return QNaN64
}
i, exact := e.Int64x()
if !exact {
return QNaN64
}
return scaleBInt(d, &dp, int(i))
}
func (d Decimal64) ScaleBInt(i int) Decimal64 {
var dp decParts
dp.unpack(d)
if !dp.fl.normal() || dp.isZero() {
return d
}
return scaleBInt(d, &dp, i)
}
func scaleBInt(d Decimal64, dp *decParts, i int) Decimal64 {
dp.exp += int16(i)
for dp.significand.lo < decimal64Base && dp.exp > -expOffset {
dp.exp--
dp.significand.lo *= 10
}
switch {
case dp.exp > expMax:
return Infinity64.CopySign(d)
case dp.exp < -expOffset:
for dp.exp < -expOffset {
dp.exp++
dp.significand.lo /= 10
}
if dp.significand.lo == 0 {
return Zero64.CopySign(d)
}
}
return dp.decimal64()
}
// Class returns a string representing the number's 'type' that the decimal is.
// It can be one of the following:
//
// - "+Normal"
// - "-Normal"
// - "+Subnormal"
// - "-Subnormal"
// - "+Zero"
// - "-Zero"
// - "+Infinity"
// - "-Infinity"
// - "NaN"
// - "sNaN"
func (d Decimal64) Class() string {
var dp decParts
dp.unpack(d)
if dp.fl == flSNaN {
return "sNaN"
} else if dp.fl.nan() {
return "NaN"
}
switch {
case dp.fl == flInf:
return "+Infinity-Infinity"[9*dp.sign : 9*(dp.sign+1)]
case dp.isZero():
return "+Zero-Zero"[5*dp.sign : 5*(dp.sign+1)]
case dp.isSubnormal():
return "+Subnormal-Subnormal"[10*dp.sign : 10*(dp.sign+1)]
}
return "+Normal-Normal"[7*dp.sign : 7*(dp.sign+1)]
}
func checkNan(d, e Decimal64, dp, ep *decParts) (Decimal64, bool) {
dp.fl = d.flavor()
ep.fl = e.flavor()
switch {
case dp.fl == flSNaN:
return d, true
case ep.fl == flSNaN:
return e, true
case dp.fl == flQNaN:
return d, true
case ep.fl == flQNaN:
return e, true
default:
dp.unpackV2(d)
ep.unpackV2(e)
return Decimal64{}, false
}
}
// checkNan3 returns the decimal NaN that is to be propogated and true else first decimal and false
func checkNan3(d, e, f Decimal64, dp, ep, fp *decParts) (Decimal64, bool) {
dp.fl = d.flavor()
ep.fl = e.flavor()
fp.fl = f.flavor()
switch {
case dp.fl == flSNaN:
return d, true
case ep.fl == flSNaN:
return e, true
case fp.fl == flSNaN:
return f, true
case dp.fl == flQNaN:
return d, true
case ep.fl == flQNaN:
return e, true
case fp.fl == flQNaN:
return f, true
default:
dp.unpackV2(d)
ep.unpackV2(e)
fp.unpackV2(f)
return Decimal64{}, false
}
}