forked from swissmicros/SDKdemo
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdecimal.cc
3633 lines (3173 loc) · 99.9 KB
/
decimal.cc
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ****************************************************************************
// decimal.cc DB48X project
// ****************************************************************************
//
// File Description:
//
// Variable-precision decimal implementation
//
// This is intended to save some code space when running on DM42,
// while improving the avaiable precision.
// The bid128 implementation takes 59.7% of the PGM space and 79.7%
// of the entire ELF file size. We can probably do better.
//
//
// ****************************************************************************
// (C) 2023 Christophe de Dinechin <[email protected]>
// This software is licensed under the terms outlined in LICENSE.txt
// ****************************************************************************
// This file is part of DB48X.
//
// DB48X is free software: you can redistribute it and/or modify
// it under the terms outlined in the LICENSE.txt file
//
// DB48X is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// ****************************************************************************
#include "decimal.h"
#include "arithmetic.h"
#include "bignum.h"
#include "constants.h"
#include "fraction.h"
#include "parser.h"
#include "renderer.h"
#include "runtime.h"
#include "settings.h"
#include "utf8.h"
#include <inttypes.h>
RECORDER(decimal, 32, "Variable-precision decimal data type");
RECORDER(decimal_error, 32, "Variable-precision decimal data type");
// ============================================================================
//
// Object interface
//
// ============================================================================
SIZE_BODY(decimal)
// ----------------------------------------------------------------------------
// Compute the size of a decimal number
// ----------------------------------------------------------------------------
{
byte_p p = o->payload();
large exp = leb128<large>(p); (void) exp;
size_t nkigits = leb128<size_t>(p);
p += (nkigits * 10 + 7) / 8;
return ptrdiff(p, o);
}
HELP_BODY(decimal)
// ----------------------------------------------------------------------------
// Help topic for decimal numbers
// ----------------------------------------------------------------------------
{
return utf8("Decimal numbers");
}
static bool normalize(object::id type,
decimal::kint *&rb,
size_t &rs,
large &re)
// ----------------------------------------------------------------------------
// Normalize a result to have no leading or trailing zero
// ----------------------------------------------------------------------------
{
// Strip leading zeroes three by three
while (rs && *rb == 0)
{
re -= 3;
rb++;
rs--;
}
// Strip up to two individual leading zeroes
if (rs && *rb < 100)
{
re -= 1 + (*rb < 10);
uint hmul = *rb < 10 ? 100 : 10;
uint lmul = 1000 / hmul;
for (size_t ko = 0; ko < rs; ko++)
{
decimal::kint next = ko + 1 < rs ? rb[ko + 1] : 0;
rb[ko] = (rb[ko] * hmul + next / lmul) % 1000;
}
}
// Strip trailing zeroes
while (rs && rb[rs-1] == 0)
rs--;
// If result is zero, set exponent to 0
if (!rs)
re = 0;
// Check overflow and underflow
large maxexp = large(Settings.MaximumDecimalExponent());
if (re - 1 < -maxexp)
{
bool negative = type == object::ID_neg_decimal;
if (Settings.UnderflowError())
{
if (negative)
rt.negative_underflow_error();
else
rt.positive_underflow_error();
return false;
}
if (negative)
Settings.NegativeUnderflowIndicator(true);
else
Settings.PositiveUnderflowIndicator(true);
re = 0;
rs = 0;
}
else if (re - 1 > maxexp)
{
if (Settings.OverflowError())
{
rt.overflow_error();
return false;
}
Settings.OverflowIndicator(true);
re = maxexp + 2;
}
return true;
}
bool decimal::is_infinity() const
// ----------------------------------------------------------------------------
// Check if the value overflowed and represents an infinity
// ----------------------------------------------------------------------------
{
return exponent() > large(Settings.MaximumDecimalExponent());
}
PARSE_BODY(decimal)
// ----------------------------------------------------------------------------
// Try to parse this as an decimal
// ----------------------------------------------------------------------------
// Note that this does not try to parse named constants like "inf" or "NaN"
{
gcutf8 source = p.source;
gcutf8 s = source;
gcutf8 last = source + p.length;
id type = ID_decimal;
scribble scr;
// Skip leading sign
if (*s == '+' || *s == '-')
{
// In an equation, `1 + 3` should interpret `+` as an infix
if (p.precedence < 0)
return SKIP;
if (*s == '-')
type = ID_neg_decimal;
++s;
}
// Scan digits and decimal dot
kint kigit = 0;
uint kigc = 0;
large exponent = 0;
int decimalDot = -1;
size_t digits = 0;
bool zeroes = true;
unicode sep = Settings.NumberSeparator();
unicode expsep = Settings.ExponentSeparator();
while (+s < +last)
{
unicode cp = utf8_codepoint(s);
if (cp == sep)
{
s = utf8_next(+s);
continue;
}
if (cp >= '0' && cp <= '9')
{
digits++;
if (!zeroes || cp != '0')
{
if (decimalDot < 0)
exponent++;
kigit = kigit * 10 + (cp - '0');
if (++kigc == 3)
{
kint *kigp = (kint *) rt.allocate(sizeof(kint));
if (!kigp)
return ERROR;
*kigp = kigit;
kigc = 0;
kigit = 0;
}
zeroes = false;
}
else if (decimalDot >= 0)
{
exponent--;
}
}
else if (decimalDot < 0 && (cp == '.' || cp == ','))
{
decimalDot = +s - +source;
}
else
{
break;
}
++s;
}
if (!digits)
return SKIP;
if (kigc)
{
while (kigc++ < 3)
kigit *= 10;
kint *kigp = (kint *) rt.allocate(sizeof(kint));
if (!kigp)
return ERROR;
*kigp = kigit;
kigc = 0;
kigit = 0;
}
// Check how many digits were given
const size_t maxdigits = Settings.Precision();
if (Settings.TooManyDigitsErrors() && digits > maxdigits)
{
rt.mantissa_error().source(source, digits + (decimalDot >= 0));
return ERROR;
}
// Check if we were given an exponent
if (+s < +last)
{
unicode cp = utf8_codepoint(+s);
if (cp == 'e' || cp == 'E' || cp == expsep)
{
large expval = 0;
bool expneg = false;
s = utf8_next(s);
unicode sign = utf8_codepoint(s);
if (sign == '+' || sign == '-' || sign == L'⁻')
{
expneg = sign == '-' || sign == L'⁻';
s = utf8_next(s);
}
bool expok = false;
while (+s < +last)
{
unicode expchar = utf8_codepoint(s);
uint expdig = fancy_digit_value(expchar, true);
if (expdig >= 10)
break;
expval = expval * 10 + expdig;
s = utf8_next(s);
expok = true;
}
if (!expok)
{
rt.exponent_error().source(s);
return ERROR;
}
exponent += expneg ? -expval : expval;
}
}
// Normalize the parsed value (#762)
kint *rb = (kint *) scr.scratch();
size_t rs = scr.growth() / sizeof(kint);
if (!normalize(type, rb, rs, exponent))
return ERROR;
// Success: build the resulting number
gcp<kint> kigits = rb;
size_t nkigs = rs;
p.length = +s - +source;
p.out = rt.make<decimal>(type, exponent, nkigs, kigits);
return p.out ? OK : ERROR;
}
RENDER_BODY(decimal)
// ----------------------------------------------------------------------------
// Render the decimal number into the given renderer
// ----------------------------------------------------------------------------
{
// Read information about the number
info sh = o->shape();
large exponent = sh.exponent;
size_t nkigits = sh.nkigits;
gcbytes base = sh.base;
decimal_g d = o;
bool negative = o->type() == ID_neg_decimal;
// Read formatting information from the renderer
r.flush();
bool editing = r.editing();
size_t rsize = r.size();
// Read settings
settings &ds = Settings;
id mode = ds.DisplayMode();
int dispdigs = ds.DisplayDigits();
int digits = dispdigs;
int std_exp = ds.StandardExponent();
bool showdec = ds.TrailingDecimal();
unicode space = ds.NumberSeparator();
uint mant_spc = ds.MantissaSpacing();
uint frac_spc = ds.FractionSpacing();
bool fancy = ds.FancyExponent();
char decimal = ds.DecimalSeparator(); // Can be '.' or ','
// Compute mantissa exponent, i.e. count of non-zero digits
large mexp = nkigits * 3;
int rmdigit = 0;
while (mexp > 0)
{
kint k = kigit(+base, mexp / 3 - 1);
if (k == 0)
{
mexp -= 3;
continue;
}
rmdigit = k % 10;
if (rmdigit == 0)
{
mexp--;
k /= 10;
rmdigit = k % 10;
if (rmdigit == 0)
{
mexp--;
k /= 10;
rmdigit = k;
}
}
break;
}
if (editing)
{
mode = object::ID_Std;
digits += mexp;
fancy = false;
showdec = true;
}
if (mode == object::ID_Std)
mode = object::ID_Sig;
static uint16_t fancy_digit[10] =
{
L'⁰', L'¹', L'²', L'³', L'⁴',
L'⁵', L'⁶', L'⁷', L'⁸', L'⁹'
};
// Emit sign if necessary
if (negative)
{
r.put('-');
rsize++;
}
// Loop checking for overflow
bool overflow = false;
do
{
// Position where we will emit the decimal dot when there is an exponent
int decpos = 1;
// Mantissa is between 0 and 1
large realexp = exponent - 1;
// Check if we need to switch to scientific notation in normal mode
// On the negative exponents, we switch when digits would be lost on
// display compared to actual digits. This is consistent with how HP
// calculators do it. e.g 1.234556789 when divided by 10 repeatedly
// switches to scientific notation at 1.23456789E-5, but 1.23 at
// 1.23E-11 and 1.2 at 1.2E-12 (on an HP50G with 12 digits).
// This is not symmetrical. Positive exponents switch at 1E12.
// Note that the behaviour here is purposely different than HP's
// when in FIX mode. In FIX 5, for example, 1.2345678E-5 is shown
// on HP50s as 0.00001, and is shown here as 1.23457E-5, which I believe
// is more useful. This behaviour is enabled by setting
// MinimumSignificantDigits to a non-zero value. If the value is zero,
// FIX works like on HP. Also, since DB48X can compute on many digits,
// and counting zeroes can be annoying, there is a separate setting,
// StandardExponent, for when to switch to scientific notation.
bool hasexp = mode == object::ID_Sci || mode == object::ID_Eng;
if (!hasexp)
{
if (realexp < 0)
{
// Need to round up if last digit is above 5
bool roundup = rmdigit >= 5;
int shown = digits + realexp + roundup;
int minfix = ds.MinimumSignificantDigits();
if (minfix < 0)
{
if (shown < 0)
{
nkigits = 0;
realexp = -digits;
}
}
else
{
if (minfix > mexp)
minfix = mexp;
hasexp = shown < minfix || realexp < -std_exp;
}
}
else
{
hasexp = realexp >= std_exp;
if (!hasexp)
decpos = realexp + 1;
}
}
// Position where we emit spacing (at sep == 0)
// 10_000_000 with mant_spc = 3
// sep=10-210-210
uint sep = mant_spc ? (decpos - 1) % mant_spc : ~0U;
// Number of decimals to show is given number of digits for most modes
// (This counts *all* digits for standard / SIG mode)
int decimals = digits;
// Write leading zeroes if necessary
if (!hasexp && realexp < 0)
{
// HP RPL calculators don't show leading 0, i.e. 0.5 shows as .5,
// but this is only in STD mode, not in other modes.
// This is pure evil and inconsistent with all older HP calculators
// (which, granted, did not have STD mode) and later ones (Prime)
// So let's decide that 0.3 will show as 0.3 in STD mode and not .3
if (Settings.LeadingZero())
r.put('0');
decpos--; // Don't emit the decimal separator twice
// Emit decimal dot and leading zeros on fractional part
if (showdec || realexp < 0)
r.put(decimal);
sep = frac_spc-1;
for (int zeroes = realexp + 1; zeroes < 0; zeroes++)
{
r.put('0');
if (sep-- == 0)
{
r.put(space);
sep = frac_spc - 1;
}
decimals--;
}
}
// Adjust exponent being displayed for engineering mode
large dispexp = realexp;
bool engmode = mode == object::ID_Eng;
if (engmode)
{
int offset = dispexp >= 0 ? dispexp % 3 : (dispexp - 2) % 3 + 2;
decpos += offset;
dispexp -= offset;
if (mant_spc)
sep = (sep + offset) % mant_spc;
decimals += 1;
}
// Copy significant digits, inserting decimal separator when needed
bool sigmode = mode == object::ID_Sig;
size_t lastnz = r.size();
size_t midx = 0;
uint decade = 0;
kint md = 0;
kint d = 0;
while (midx < nkigits || decade)
{
// Find next digit and emit it
if (decade == 0)
{
if (overflow)
{
md = 1;
decade = 1;
midx = nkigits;
}
else
{
md = kigit(+base, midx++);
decade = 3;
}
}
decade--;
d = decade == 2 ? md / 100 : (decade == 1 ? (md / 10) : md) % 10;
if (decpos <= 0 && decimals <= 0)
{
decade++; // Enable rounding of last digit
break;
}
r.put(char('0' + d));
decpos--;
// Check if we will need to eliminate trailing zeros
if (decpos >= 0 || d)
lastnz = r.size();
// Insert spacing on the left of the decimal mark
bool more = (midx < nkigits || decade) || !sigmode || decpos > 0;
if (sep-- == 0 && more && decimals > 1)
{
if (decpos)
{
r.put(space);
if (decpos > 0)
lastnz = r.size();
}
sep = (decpos > 0 ? mant_spc : frac_spc) - 1;
}
if (decpos == 0 && (more || showdec))
{
r.put(decimal);
lastnz = r.size() - (!showdec && (sigmode || digits == 0));
sep = frac_spc - 1;
}
// Count decimals after decimal separator, except in SIG mode
// where we count all significant digits being displayed
if (decpos < 0 || sigmode || engmode)
decimals--;
}
// Check if we need some rounding on what is being displayed
if ((midx < nkigits || decade) && d >= 5)
{
size_t rsz = r.size();
char *start = (char *) r.text() + rsize;
char *rptr = start + rsz - rsize;
bool rounding = true;
bool stripzeros = mode == object::ID_Sig;
while (rounding && --rptr >= start)
{
if (*rptr >= '0' && *rptr <= '9') // Do not convert '.' or '-'
{
*rptr += 1;
rounding = *rptr > '9';
if (rounding)
{
*rptr -= 10;
if (stripzeros && *rptr == '0' && rptr > start)
{
r.unwrite(1);
decimals++;
decpos++;
uint spc = decpos > 0 ? mant_spc : frac_spc;
sep = (sep + 1) % spc;
}
else
{
stripzeros = false;
}
}
}
else if (*rptr == decimal)
{
stripzeros = false;
if (!showdec)
r.unwrite(1);
}
else if (stripzeros) // Inserted separator
{
r.unwrite(1);
sep = 0;
}
}
// If we ran past the first digit, we overflowed during rounding
// Need to re-run with the next larger exponent
// This can only occur with a conversion of 9.9999 to 1
if (rounding)
{
overflow = true;
exponent++;
r.reset_to(rsize);
continue;
}
// Check if we need to reinsert the last separator
if (sep-- == 0 && decpos > 0 && decimals > 1)
{
r.put(space);
sep = (decpos > 0 ? mant_spc : frac_spc) - 1;
}
}
// Return to position of last inserted zero
else if ((!decpos || mode == object::ID_Sig) && r.size() > lastnz)
{
r.reset_to(lastnz);
}
// Do not add trailing zeroes in standard mode
if (sigmode)
{
decimals = decpos > 0 ? decpos : 0;
}
else if (mode == object::ID_Fix && decpos > 0)
{
decimals = digits + decpos;
}
// Add trailing zeroes if necessary
while (decimals > 0)
{
r.put('0');
decpos--;
if (sep-- == 0 && decimals > 1)
{
if (decpos)
r.put(space);
sep = (decpos > 0 ? mant_spc : frac_spc) - 1;
}
if (decpos == 0 && showdec)
r.put(decimal);
decimals--;
}
// Add exponent if necessary
if (hasexp)
{
r.put(ds.ExponentSeparator());
if (fancy)
{
char expbuf[32];
size_t written = snprintf(expbuf, 32, "%" PRId64, dispexp);
for (uint e = 0; e < written; e++)
{
char c = expbuf[e];
unicode u = c == '-' ? L'⁻' : fancy_digit[c - '0'];
r.put(u);
}
}
else
{
r.printf("%d", dispexp);
}
}
return r.size();
} while (overflow);
return 0;
}
// ============================================================================
//
// Conversions
//
// ============================================================================
ularge decimal::as_unsigned(bool magnitude) const
// ----------------------------------------------------------------------------
// Convert a decimal value to an unsigned value
// ----------------------------------------------------------------------------
// When magnitude is set, we return magnitude for negative values
{
info s = shape();
large exp = s.exponent;
size_t nkigits = s.nkigits;
byte_p bp = s.base;
if (exp < 0 || (!magnitude && type() == ID_neg_decimal))
return 0;
// If we overflow in the computation, return a "maxint"
if (exp >= 19)
return ~0UL;
ularge xp = exp;
ularge pow = 1;
ularge mul = 10;
while (xp && pow)
{
if (xp & 1)
pow *= mul;
mul = mul * mul;
xp /= 2;
}
if (!pow)
return ~0ULL;
ularge result = 0;
for (size_t m = 0; m < nkigits && pow; m++)
{
kint d = kigit(bp, m);
ularge next = result + d * pow / 1000;
if (next < result)
return ~0ULL;
result = next;
pow /= 1000;
}
return result;
}
large decimal::as_integer() const
// ----------------------------------------------------------------------------
// Convert a decimal value to an integer
// ----------------------------------------------------------------------------
{
large result = (large) as_unsigned(true);
if (result == ~0L)
result = 0x7FFFFFFFFFFFFFFFL;
if (type() == ID_neg_decimal)
result = -result;
return result;
}
int32_t decimal::as_int32() const
// ----------------------------------------------------------------------------
// Convert a decimal value to an int32_t
// ----------------------------------------------------------------------------
{
large result = (large) as_unsigned(true);
if (result == ~0L || result >= 0x80000000L)
result = 0x7FFFFFFF;
if (type() == ID_neg_decimal)
result = -result;
return (int32_t) result;
}
decimal_p decimal::from_integer(integer_p value)
// ----------------------------------------------------------------------------
// Create a decimal value from an integer
// ----------------------------------------------------------------------------
{
if (!value)
return nullptr;
id itype = value->type();
id type = itype == ID_neg_integer ? ID_neg_decimal : ID_decimal;
ularge magnitude = value->value<ularge>();
return make(type, magnitude);
}
decimal_p decimal::from_bignum(bignum_p valuep)
// ----------------------------------------------------------------------------
// Create a decimal number from a bignum
// ----------------------------------------------------------------------------
{
if (!valuep)
return nullptr;
id itype = valuep->type();
id type = itype == ID_neg_bignum ? ID_neg_decimal : ID_decimal;
decimal_g result = make(type, 0);
decimal_g digits;
large exp = 0;
bignum_g value = valuep;
bignum_g div = bignum::make(1000000000000UL);
bignum_g kigit;
while (!value->is_zero())
{
if (!bignum::quorem(value, div, itype, &value, &kigit))
return nullptr;
ularge kigval = kigit->value<ularge>();
digits = make(type, kigval, exp);
result = result + digits;
exp += 12;
}
return result;
}
decimal_p decimal::from_random_seed(bignum_p valuep)
// ----------------------------------------------------------------------------
// Create a decimal number from a bignum interpreted as a random seed
// ----------------------------------------------------------------------------
{
if (!valuep)
return nullptr;
id itype = valuep->type();
id type = ID_decimal;
decimal_g result = make(type, 0);
decimal_g digits;
large exp = 0;
bignum_g value = valuep;
bignum_g div = bignum::make(1000000000000UL);
bignum_g kigit;
while (!value->is_zero())
{
exp -= 12;
if (!bignum::quorem(value, div, itype, &value, &kigit))
return nullptr;
ularge kigval = kigit->value<ularge>();
digits = make(type, kigval, exp);
result = result + digits;
}
return result;
}
decimal_p decimal::from_fraction(fraction_p value)
// ----------------------------------------------------------------------------
// Build a decimal number from a fraction
// ----------------------------------------------------------------------------
{
id type = value->type();
if (type == ID_big_fraction || type == ID_neg_big_fraction)
return from_big_fraction(big_fraction_p(value));
decimal_g num = decimal::make(value->numerator_value());
decimal_g den = decimal::make(value->denominator_value());
if (type == ID_neg_fraction)
num = -num;
return num / den;
}
decimal_p decimal::from_big_fraction(big_fraction_p value)
// ------------------------------------------------------------------------
// Build a decimal number from a big fraction
// ------------------------------------------------------------------------
{
decimal_g num = decimal::from_bignum(value->numerator());
decimal_g den = decimal::from_bignum(value->denominator());
return num / den;
}
decimal::class_type decimal::fpclass() const
// ----------------------------------------------------------------------------
// Return the floating-point class for the decimal number
// ----------------------------------------------------------------------------
{
info s = shape();
size_t nkigits = s.nkigits;
byte_p bp = s.base;
bool neg = type() == ID_neg_decimal;
if (nkigits == 0)
return neg ? negativeZero : positiveZero;
kint d = kigit(bp, 0);
if (d >= 1000)
{
if (d == infinity)
return neg ? negativeInfinity : positiveInfinity;
}
if (d < 100)
return neg ? negativeSubnormal : positiveSubnormal;
return neg ? negativeNormal : positiveNormal;
}
bool decimal::is_normal() const
// ----------------------------------------------------------------------------
// Return true if the number is normal (not NaN, not infinity)
// ----------------------------------------------------------------------------
{
info s = shape();
if (s.exponent > large(Settings.MaximumDecimalExponent())) // Infinity
return false;
size_t nkigits = s.nkigits;
byte_p bp = s.base;
if (nkigits == 0)
return true;
kint d = kigit(bp, 0);
return d < 1000;
}
bool decimal::is_zero() const
// ----------------------------------------------------------------------------
// The normal zero has no digits
// ----------------------------------------------------------------------------
{
return shape().nkigits == 0;
}
bool decimal::is_one() const
// ----------------------------------------------------------------------------
// Normal representation for one
// ----------------------------------------------------------------------------
{
if (type() == ID_neg_decimal)
return false;
info s = shape();
large exp = s.exponent;
size_t nkigits = s.nkigits;
byte_p bp = s.base;
return exp == 1 && nkigits == 1 && kigit(bp, 0) == 100;
}
bool decimal::is_negative() const
// ----------------------------------------------------------------------------
// Return true if the value is strictly negative
// ----------------------------------------------------------------------------
{
if (type() == ID_decimal)
return false;
return shape().nkigits != 0;
}
bool decimal::is_negative_or_zero() const
// ----------------------------------------------------------------------------
// Return true if the value is zero o rnegative
// ------------------------------------------------------------------------
{
if (type() == ID_neg_decimal)
return true;
return shape().nkigits == 0;
}
bool decimal::is_magnitude_less_than(uint kig, large exponent) const
// ----------------------------------------------------------------------------
// Check if a given number is less than specified number in magnitude
// ----------------------------------------------------------------------------
{
info s = shape();
large exp = s.exponent;
size_t nkigits = s.nkigits;
byte_p bp = s.base;
if (exp != exponent)
return exp < exponent;
return nkigits == 0 || kigit(bp, 0) <= kig;
}
decimal_p decimal::truncate(large to_exp) const
// ----------------------------------------------------------------------------
// Truncate a given decimal number (round towards zero)
// ----------------------------------------------------------------------------
{
info s = shape();
// If we have 1E-3 and round at 0, return zero
large exp = s.exponent;
if (exp < to_exp)
return make(0);
// If rounding 10000 (10^4) to 0, we can copy 1 kigit as is
size_t copy = (exp - to_exp) / 3;
size_t nkigits = s.nkigits;
if (copy >= nkigits)
return this; // We copy everything
gcbytes bp = s.base;
id ty = type();
scribble scr;
for (size_t i = 0; i <= copy; i++)
{
kint k = kigit(+bp, i);
if (i == copy)
{
size_t rm = (exp - to_exp) % 3;
if (rm == 0)
k = 0;
else if (rm == 1)
k -= k % 100;
else if (rm == 2)
k -= k % 10;
}
kint *kp = (kint *) rt.allocate(sizeof(kint));