/
bigdecimal.c
4722 lines (4348 loc) · 121 KB
/
bigdecimal.c
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
/*
*
* Ruby BigDecimal(Variable decimal precision) extension library.
*
* Copyright(C) 2002 by Shigeo Kobayashi(shigeo@tinyforest.gr.jp)
*
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file
* of this BigDecimal distribution.
*
* NOTE: Change log in this source removed to reduce source code size.
* See rev. 1.25 if needed.
*
*/
#include "ruby/ruby.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <float.h>
#include <math.h>
#include "math.h"
/* #define ENABLE_NUMERIC_STRING */
VALUE rb_cBigDecimal;
#include "bigdecimal.h"
/* MACRO's to guard objects from GC by keeping them in stack */
#define ENTER(n) volatile VALUE vStack[n];int iStack=0
#define PUSH(x) vStack[iStack++] = (unsigned long)(x);
#define SAVE(p) PUSH(p->obj);
#define GUARD_OBJ(p,y) {p=y;SAVE(p);}
/*
* ================== Ruby Interface part ==========================
*/
#define DoSomeOne(x,y,f) rb_num_coerce_bin(x,y,f)
#if 0
/* BigDecimal provides arbitrary-precision floating point decimal arithmetic.
*
* Copyright (C) 2002 by Shigeo Kobayashi <shigeo@tinyforest.gr.jp>.
* You may distribute under the terms of either the GNU General Public
* License or the Artistic License, as specified in the README file
* of the BigDecimal distribution.
*
* Documented by mathew <meta@pobox.com>.
*
* = Introduction
*
* Ruby provides built-in support for arbitrary precision integer arithmetic.
* For example:
*
* 42**13 -> 1265437718438866624512
*
* BigDecimal provides similar support for very large or very accurate floating
* point numbers.
*
* Decimal arithmetic is also useful for general calculation, because it
* provides the correct answers people expect--whereas normal binary floating
* point arithmetic often introduces subtle errors because of the conversion
* between base 10 and base 2. For example, try:
*
* sum = 0
* for i in (1..10000)
* sum = sum + 0.0001
* end
* print sum
*
* and contrast with the output from:
*
* require 'bigdecimal'
*
* sum = BigDecimal.new("0")
* for i in (1..10000)
* sum = sum + BigDecimal.new("0.0001")
* end
* print sum
*
* Similarly:
*
* (BigDecimal.new("1.2") - BigDecimal("1.0")) == BigDecimal("0.2") -> true
*
* (1.2 - 1.0) == 0.2 -> false
*
* = Special features of accurate decimal arithmetic
*
* Because BigDecimal is more accurate than normal binary floating point
* arithmetic, it requires some special values.
*
* == Infinity
*
* BigDecimal sometimes needs to return infinity, for example if you divide
* a value by zero.
*
* BigDecimal.new("1.0") / BigDecimal.new("0.0") -> infinity
*
* BigDecimal.new("-1.0") / BigDecimal.new("0.0") -> -infinity
*
* You can represent infinite numbers to BigDecimal using the strings
* 'Infinity', '+Infinity' and '-Infinity' (case-sensitive)
*
* == Not a Number
*
* When a computation results in an undefined value, the special value NaN
* (for 'not a number') is returned.
*
* Example:
*
* BigDecimal.new("0.0") / BigDecimal.new("0.0") -> NaN
*
* You can also create undefined values. NaN is never considered to be the
* same as any other value, even NaN itself:
*
* n = BigDecimal.new('NaN')
*
* n == 0.0 -> nil
*
* n == n -> nil
*
* == Positive and negative zero
*
* If a computation results in a value which is too small to be represented as
* a BigDecimal within the currently specified limits of precision, zero must
* be returned.
*
* If the value which is too small to be represented is negative, a BigDecimal
* value of negative zero is returned. If the value is positive, a value of
* positive zero is returned.
*
* BigDecimal.new("1.0") / BigDecimal.new("-Infinity") -> -0.0
*
* BigDecimal.new("1.0") / BigDecimal.new("Infinity") -> 0.0
*
* (See BigDecimal.mode for how to specify limits of precision.)
*
* Note that -0.0 and 0.0 are considered to be the same for the purposes of
* comparison.
*
* Note also that in mathematics, there is no particular concept of negative
* or positive zero; true mathematical zero has no sign.
*/
void
Init_BigDecimal()
{
/* This is a #if-ed out function to fool Rdoc into documenting the class. */
/* The real init function is Init_bigdecimal() further down. */
}
#endif
/*
* Returns the BigDecimal version number.
*
* Ruby 1.8.0 returns 1.0.0.
* Ruby 1.8.1 thru 1.8.3 return 1.0.1.
*/
static VALUE
BigDecimal_version(VALUE self, SEL sel)
{
/*
* 1.0.0: Ruby 1.8.0
* 1.0.1: Ruby 1.8.1
*/
return rb_str_new2("1.0.1");
}
/*
* VP routines used in BigDecimal part
*/
static unsigned short VpGetException(void);
static void VpSetException(unsigned short f);
static void VpInternalRound(Real *c,int ixDigit,U_LONG vPrev,U_LONG v);
static int VpLimitRound(Real *c,U_LONG ixDigit);
/*
* **** BigDecimal part ****
*/
static void
BigDecimal_delete(Real *pv)
{
VpFree(pv);
}
static VALUE
ToValue(Real *p)
{
if(VpIsNaN(p)) {
VpException(VP_EXCEPTION_NaN,"Computation results to 'NaN'(Not a Number)",0);
} else if(VpIsPosInf(p)) {
VpException(VP_EXCEPTION_INFINITY,"Computation results to 'Infinity'",0);
} else if(VpIsNegInf(p)) {
VpException(VP_EXCEPTION_INFINITY,"Computation results to '-Infinity'",0);
}
return p->obj;
}
static Real *
GetVpValue(VALUE v, int must)
{
Real *pv;
VALUE bg;
char szD[128];
switch(TYPE(v))
{
case T_DATA:
if(RDATA(v)->dfree ==(void *) BigDecimal_delete) {
Data_Get_Struct(v, Real, pv);
return pv;
} else {
goto SomeOneMayDoIt;
}
break;
case T_FIXNUM:
sprintf(szD, "%ld", FIX2LONG(v));
return VpCreateRbObject(VpBaseFig() * 2 + 1, szD);
#ifdef ENABLE_NUMERIC_STRING
case T_STRING:
SafeStringValue(v);
return VpCreateRbObject(strlen(RSTRING_PTR(v)) + VpBaseFig() + 1,
RSTRING_PTR(v));
#endif /* ENABLE_NUMERIC_STRING */
case T_BIGNUM:
bg = rb_big2str(v, 10);
return VpCreateRbObject(strlen(RSTRING_PTR(bg)) + VpBaseFig() + 1,
RSTRING_PTR(bg));
default:
goto SomeOneMayDoIt;
}
SomeOneMayDoIt:
if(must) {
rb_raise(rb_eTypeError, "%s can't be coerced into BigDecimal",
rb_special_const_p(v)?
RSTRING_PTR(rb_inspect(v)):
rb_obj_classname(v)
);
}
return NULL; /* NULL means to coerce */
}
/* call-seq:
* BigDecimal.double_fig
*
* The BigDecimal.double_fig class method returns the number of digits a
* Float number is allowed to have. The result depends upon the CPU and OS
* in use.
*/
static VALUE
BigDecimal_double_fig(VALUE self, SEL sel)
{
return INT2FIX(VpDblFig());
}
/* call-seq:
* precs
*
* Returns an Array of two Integer values.
*
* The first value is the current number of significant digits in the
* BigDecimal. The second value is the maximum number of significant digits
* for the BigDecimal.
*/
static VALUE
BigDecimal_prec(VALUE self, SEL sel)
{
ENTER(1);
Real *p;
VALUE obj;
GUARD_OBJ(p,GetVpValue(self,1));
obj = rb_assoc_new(INT2NUM(p->Prec*VpBaseFig()),
INT2NUM(p->MaxPrec*VpBaseFig()));
return obj;
}
static VALUE
BigDecimal_hash(VALUE self, SEL sel)
{
ENTER(1);
Real *p;
U_LONG hash,i;
GUARD_OBJ(p,GetVpValue(self,1));
hash = (U_LONG)p->sign;
/* hash!=2: the case for 0(1),NaN(0) or +-Infinity(3) is sign itself */
if(hash==2) {
for(i = 0; i < p->Prec;i++) {
hash = 31 * hash + p->frac[i];
hash ^= p->frac[i];
}
hash += p->exponent;
}
return INT2FIX(hash);
}
static VALUE
BigDecimal_dump(VALUE self, SEL sel, int argc, VALUE *argv)
{
ENTER(5);
char sz[50];
Real *vp;
char *psz;
VALUE dummy;
rb_scan_args(argc, argv, "01", &dummy);
GUARD_OBJ(vp,GetVpValue(self,1));
sprintf(sz,"%lu:",VpMaxPrec(vp)*VpBaseFig());
psz = ALLOCA_N(char,(unsigned int)VpNumOfChars(vp,"E")+strlen(sz));
sprintf(psz,"%s",sz);
VpToString(vp, psz+strlen(psz), 0, 0);
return rb_str_new2(psz);
}
/*
* Internal method used to provide marshalling support. See the Marshal module.
*/
static VALUE
BigDecimal_load(VALUE self, SEL sel, VALUE str)
{
ENTER(2);
Real *pv;
unsigned char *pch;
unsigned char ch;
unsigned long m=0;
SafeStringValue(str);
pch = (unsigned char *)RSTRING_PTR(str);
/* First get max prec */
while((*pch)!=(unsigned char)'\0' && (ch=*pch++)!=(unsigned char)':') {
if(!ISDIGIT(ch)) {
rb_raise(rb_eTypeError, "load failed: invalid character in the marshaled string");
}
m = m*10 + (unsigned long)(ch-'0');
}
if(m>VpBaseFig()) m -= VpBaseFig();
GUARD_OBJ(pv,VpNewRbClass(m,(char *)pch,self));
m /= VpBaseFig();
if(m && pv->MaxPrec>m) pv->MaxPrec = m+1;
return ToValue(pv);
}
/* call-seq:
* BigDecimal.mode(mode, value)
*
* Controls handling of arithmetic exceptions and rounding. If no value
* is supplied, the current value is returned.
*
* Six values of the mode parameter control the handling of arithmetic
* exceptions:
*
* BigDecimal::EXCEPTION_NaN
* BigDecimal::EXCEPTION_INFINITY
* BigDecimal::EXCEPTION_UNDERFLOW
* BigDecimal::EXCEPTION_OVERFLOW
* BigDecimal::EXCEPTION_ZERODIVIDE
* BigDecimal::EXCEPTION_ALL
*
* For each mode parameter above, if the value set is false, computation
* continues after an arithmetic exception of the appropriate type.
* When computation continues, results are as follows:
*
* EXCEPTION_NaN:: NaN
* EXCEPTION_INFINITY:: +infinity or -infinity
* EXCEPTION_UNDERFLOW:: 0
* EXCEPTION_OVERFLOW:: +infinity or -infinity
* EXCEPTION_ZERODIVIDE:: +infinity or -infinity
*
* One value of the mode parameter controls the rounding of numeric values:
* BigDecimal::ROUND_MODE. The values it can take are:
*
* ROUND_UP:: round away from zero
* ROUND_DOWN:: round towards zero (truncate)
* ROUND_HALF_UP:: round up if the appropriate digit >= 5, otherwise truncate (default)
* ROUND_HALF_DOWN:: round up if the appropriate digit >= 6, otherwise truncate
* ROUND_HALF_EVEN:: round towards the even neighbor (Banker's rounding)
* ROUND_CEILING:: round towards positive infinity (ceil)
* ROUND_FLOOR:: round towards negative infinity (floor)
*
*/
static VALUE
BigDecimal_mode(VALUE self, SEL sel, int argc, VALUE *argv)
{
VALUE which;
VALUE val;
unsigned long f,fo;
if(rb_scan_args(argc,argv,"11",&which,&val)==1) val = Qnil;
Check_Type(which, T_FIXNUM);
f = (unsigned long)FIX2INT(which);
if(f&VP_EXCEPTION_ALL) {
/* Exception mode setting */
fo = VpGetException();
if(val==Qnil) return INT2FIX(fo);
if(val!=Qfalse && val!=Qtrue) {
rb_raise(rb_eTypeError, "second argument must be true or false");
return Qnil; /* Not reached */
}
if(f&VP_EXCEPTION_INFINITY) {
VpSetException((unsigned short)((val==Qtrue)?(fo|VP_EXCEPTION_INFINITY):
(fo&(~VP_EXCEPTION_INFINITY))));
}
if(f&VP_EXCEPTION_NaN) {
VpSetException((unsigned short)((val==Qtrue)?(fo|VP_EXCEPTION_NaN):
(fo&(~VP_EXCEPTION_NaN))));
}
fo = VpGetException();
return INT2FIX(fo);
}
if(VP_ROUND_MODE==f) {
/* Rounding mode setting */
fo = VpGetRoundMode();
if(val==Qnil) return INT2FIX(fo);
Check_Type(val, T_FIXNUM);
if(!VpIsRoundMode(FIX2INT(val))) {
rb_raise(rb_eTypeError, "invalid rounding mode");
return Qnil;
}
fo = VpSetRoundMode((unsigned long)FIX2INT(val));
return INT2FIX(fo);
}
rb_raise(rb_eTypeError, "first argument for BigDecimal#mode invalid");
return Qnil;
}
static U_LONG
GetAddSubPrec(Real *a, Real *b)
{
U_LONG mxs;
U_LONG mx = a->Prec;
S_INT d;
if(!VpIsDef(a) || !VpIsDef(b)) return (-1L);
if(mx < b->Prec) mx = b->Prec;
if(a->exponent!=b->exponent) {
mxs = mx;
d = a->exponent - b->exponent;
if(d<0) d = -d;
mx = mx+(U_LONG)d;
if(mx<mxs) {
return VpException(VP_EXCEPTION_INFINITY,"Exponent overflow",0);
}
}
return mx;
}
static S_INT
GetPositiveInt(VALUE v)
{
S_INT n;
Check_Type(v, T_FIXNUM);
n = FIX2INT(v);
if(n < 0) {
rb_raise(rb_eArgError, "argument must be positive");
}
return n;
}
VP_EXPORT Real *
VpNewRbClass(U_LONG mx, const char *str, VALUE klass)
{
Real *pv = VpAlloc(mx,str);
pv->obj = (VALUE)Data_Wrap_Struct(klass, 0, BigDecimal_delete, pv);
return pv;
}
VP_EXPORT Real *
VpCreateRbObject(U_LONG mx, const char *str)
{
Real *pv = VpAlloc(mx,str);
pv->obj = (VALUE)Data_Wrap_Struct(rb_cBigDecimal, 0, BigDecimal_delete, pv);
return pv;
}
/* Returns True if the value is Not a Number */
static VALUE
BigDecimal_IsNaN(VALUE self, SEL sel)
{
Real *p = GetVpValue(self,1);
if(VpIsNaN(p)) return Qtrue;
return Qfalse;
}
/* Returns True if the value is infinite */
static VALUE
BigDecimal_IsInfinite(VALUE self, SEL sel)
{
Real *p = GetVpValue(self,1);
if(VpIsPosInf(p)) return INT2FIX(1);
if(VpIsNegInf(p)) return INT2FIX(-1);
return Qnil;
}
/* Returns True if the value is finite (not NaN or infinite) */
static VALUE
BigDecimal_IsFinite(VALUE self, SEL sel)
{
Real *p = GetVpValue(self,1);
if(VpIsNaN(p)) return Qfalse;
if(VpIsInf(p)) return Qfalse;
return Qtrue;
}
/* Returns the value as an integer (Fixnum or Bignum).
*
* If the BigNumber is infinity or NaN, returns nil.
*/
static VALUE
BigDecimal_to_i(VALUE self, SEL sel)
{
ENTER(5);
int e,n,i,nf;
U_LONG v,b,j;
char *psz,*pch;
Real *p;
GUARD_OBJ(p,GetVpValue(self,1));
/* Infinity or NaN not converted. */
if(VpIsNaN(p)) {
VpException(VP_EXCEPTION_NaN,"Computation results to 'NaN'(Not a Number)",0);
return Qnil;
} else if(VpIsPosInf(p)) {
VpException(VP_EXCEPTION_INFINITY,"Computation results to 'Infinity'",0);
return Qnil;
} else if(VpIsNegInf(p)) {
VpException(VP_EXCEPTION_INFINITY,"Computation results to '-Infinity'",0);
return Qnil;
}
e = VpExponent10(p);
if(e<=0) return INT2FIX(0);
nf = VpBaseFig();
if(e<=nf) {
e = VpGetSign(p)*p->frac[0];
return INT2FIX(e);
}
psz = ALLOCA_N(char,(unsigned int)(e+nf+2));
n = (e+nf-1)/nf;
pch = psz;
if(VpGetSign(p)<0) *pch++ = '-';
for(i=0;i<n;++i) {
b = VpBaseVal()/10;
if(i>=(int)p->Prec) {
while(b) {
*pch++ = '0';
b /= 10;
}
continue;
}
v = p->frac[i];
while(b) {
j = v/b;
*pch++ = (char)(j + '0');
v -= j*b;
b /= 10;
}
}
*pch++ = 0;
return rb_cstr2inum(psz,10);
}
static VALUE
BigDecimal_induced_from(VALUE self, SEL sel, VALUE x)
{
Real *p = GetVpValue(x,1);
return p->obj;
}
/* Returns a new Float object having approximately the same value as the
* BigDecimal number. Normal accuracy limits and built-in errors of binary
* Float arithmetic apply.
*/
static VALUE
BigDecimal_to_f(VALUE self, SEL sel)
{
ENTER(1);
Real *p;
double d;
S_LONG e;
char *buf;
GUARD_OBJ(p,GetVpValue(self,1));
if(VpVtoD(&d, &e, p)!=1) return rb_float_new(d);
buf = ALLOCA_N(char,(unsigned int)VpNumOfChars(p,"E"));
VpToString(p, buf, 0, 0);
errno = 0;
d = strtod(buf, 0);
if(errno == ERANGE) {
VpException(VP_EXCEPTION_OVERFLOW,"BigDecimal to Float conversion",0);
if(d>0.0) return rb_float_new(DBL_MAX);
else return rb_float_new(-DBL_MAX);
}
return rb_float_new(d);
}
/* The coerce method provides support for Ruby type coercion. It is not
* enabled by default.
*
* This means that binary operations like + * / or - can often be performed
* on a BigDecimal and an object of another type, if the other object can
* be coerced into a BigDecimal value.
*
* e.g.
* a = BigDecimal.new("1.0")
* b = a / 2.0 -> 0.5
*
* Note that coercing a String to a BigDecimal is not supported by default;
* it requires a special compile-time option when building Ruby.
*/
static VALUE
BigDecimal_coerce(VALUE self, SEL sel, VALUE other)
{
ENTER(2);
VALUE obj;
Real *b;
if(TYPE(other) == T_FLOAT) {
obj = rb_assoc_new(other, BigDecimal_to_f(self, 0));
} else {
GUARD_OBJ(b,GetVpValue(other,1));
obj = rb_assoc_new(b->obj, self);
}
return obj;
}
static VALUE
BigDecimal_uplus(VALUE self, SEL sel)
{
return self;
}
/* call-seq:
* add(value, digits)
*
* Add the specified value.
*
* e.g.
* c = a.add(b,n)
* c = a + b
*
* digits:: If specified and less than the number of significant digits of the result, the result is rounded to that number of digits, according to BigDecimal.mode.
*/
static VALUE
BigDecimal_add(VALUE self, SEL sel, VALUE r)
{
ENTER(5);
Real *c, *a, *b;
U_LONG mx;
GUARD_OBJ(a,GetVpValue(self,1));
b = GetVpValue(r,0);
if(!b) return DoSomeOne(self,r,'+');
SAVE(b);
if(VpIsNaN(b)) return b->obj;
if(VpIsNaN(a)) return a->obj;
mx = GetAddSubPrec(a,b);
if(mx==(-1L)) {
GUARD_OBJ(c,VpCreateRbObject(VpBaseFig() + 1, "0"));
VpAddSub(c, a, b, 1);
} else {
GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0"));
if(!mx) {
VpSetInf(c,VpGetSign(a));
} else {
VpAddSub(c, a, b, 1);
}
}
return ToValue(c);
}
/* call-seq:
* sub(value, digits)
*
* Subtract the specified value.
*
* e.g.
* c = a.sub(b,n)
* c = a - b
*
* digits:: If specified and less than the number of significant digits of the result, the result is rounded to that number of digits, according to BigDecimal.mode.
*/
static VALUE
BigDecimal_sub(VALUE self, SEL sel, VALUE r)
{
ENTER(5);
Real *c, *a, *b;
U_LONG mx;
GUARD_OBJ(a,GetVpValue(self,1));
b = GetVpValue(r,0);
if(!b) return DoSomeOne(self,r,'-');
SAVE(b);
if(VpIsNaN(b)) return b->obj;
if(VpIsNaN(a)) return a->obj;
mx = GetAddSubPrec(a,b);
if(mx==(-1L)) {
GUARD_OBJ(c,VpCreateRbObject(VpBaseFig() + 1, "0"));
VpAddSub(c, a, b, -1);
} else {
GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0"));
if(!mx) {
VpSetInf(c,VpGetSign(a));
} else {
VpAddSub(c, a, b, -1);
}
}
return ToValue(c);
}
static VALUE
BigDecimalCmp(VALUE self, VALUE r,char op)
{
ENTER(5);
S_INT e;
Real *a, *b;
GUARD_OBJ(a,GetVpValue(self,1));
b = GetVpValue(r,0);
if(!b) {
ID f = 0;
switch(op)
{
case '*': f = rb_intern("<=>");break;
case '=': f = rb_intern("=="); break;
case '!': f = rb_intern("!="); break;
case 'G': f = rb_intern(">="); break;
case 'L': f = rb_intern("<="); break;
case '>': case '<': f = (ID)op; break;
}
return rb_num_coerce_cmp(self,r,f);
}
SAVE(b);
e = VpComp(a, b);
if(e==999) return Qnil;
switch(op)
{
case '*': return INT2FIX(e); /* any op */
case '=': if(e==0) return Qtrue ; return Qfalse;
case '!': if(e!=0) return Qtrue ; return Qfalse;
case 'G': if(e>=0) return Qtrue ; return Qfalse;
case '>': if(e> 0) return Qtrue ; return Qfalse;
case 'L': if(e<=0) return Qtrue ; return Qfalse;
case '<': if(e< 0) return Qtrue ; return Qfalse;
}
rb_bug("Undefined operation in BigDecimalCmp()");
}
/* Returns True if the value is zero. */
static VALUE
BigDecimal_zero(VALUE self, SEL sel)
{
Real *a = GetVpValue(self,1);
return VpIsZero(a) ? Qtrue : Qfalse;
}
/* Returns True if the value is non-zero. */
static VALUE
BigDecimal_nonzero(VALUE self, SEL sel)
{
Real *a = GetVpValue(self,1);
return VpIsZero(a) ? Qnil : self;
}
/* The comparison operator.
* a <=> b is 0 if a == b, 1 if a > b, -1 if a < b.
*/
static VALUE
BigDecimal_comp(VALUE self, SEL sel, VALUE r)
{
return BigDecimalCmp(self, r, '*');
}
/*
* Tests for value equality; returns true if the values are equal.
*
* The == and === operators and the eql? method have the same implementation
* for BigDecimal.
*
* Values may be coerced to perform the comparison:
*
* BigDecimal.new('1.0') == 1.0 -> true
*/
static VALUE
BigDecimal_eq(VALUE self, SEL sel, VALUE r)
{
return BigDecimalCmp(self, r, '=');
}
/* call-seq:
* a < b
*
* Returns true if a is less than b. Values may be coerced to perform the
* comparison (see ==, coerce).
*/
static VALUE
BigDecimal_lt(VALUE self, SEL sel, VALUE r)
{
return BigDecimalCmp(self, r, '<');
}
/* call-seq:
* a <= b
*
* Returns true if a is less than or equal to b. Values may be coerced to
* perform the comparison (see ==, coerce).
*/
static VALUE
BigDecimal_le(VALUE self, SEL sel, VALUE r)
{
return BigDecimalCmp(self, r, 'L');
}
/* call-seq:
* a > b
*
* Returns true if a is greater than b. Values may be coerced to
* perform the comparison (see ==, coerce).
*/
static VALUE
BigDecimal_gt(VALUE self, SEL sel, VALUE r)
{
return BigDecimalCmp(self, r, '>');
}
/* call-seq:
* a >= b
*
* Returns true if a is greater than or equal to b. Values may be coerced to
* perform the comparison (see ==, coerce)
*/
static VALUE
BigDecimal_ge(VALUE self, SEL sel, VALUE r)
{
return BigDecimalCmp(self, r, 'G');
}
static VALUE
BigDecimal_neg(VALUE self, SEL sel)
{
ENTER(5);
Real *c, *a;
GUARD_OBJ(a,GetVpValue(self,1));
GUARD_OBJ(c,VpCreateRbObject(a->Prec *(VpBaseFig() + 1), "0"));
VpAsgn(c, a, -1);
return ToValue(c);
}
/* call-seq:
* mult(value, digits)
*
* Multiply by the specified value.
*
* e.g.
* c = a.mult(b,n)
* c = a * b
*
* digits:: If specified and less than the number of significant digits of the result, the result is rounded to that number of digits, according to BigDecimal.mode.
*/
static VALUE
BigDecimal_mult(VALUE self, SEL sel, VALUE r)
{
ENTER(5);
Real *c, *a, *b;
U_LONG mx;
GUARD_OBJ(a,GetVpValue(self,1));
b = GetVpValue(r,0);
if(!b) return DoSomeOne(self,r,'*');
SAVE(b);
mx = a->Prec + b->Prec;
GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0"));
VpMult(c, a, b);
return ToValue(c);
}
static VALUE
BigDecimal_divide(Real **c, Real **res, Real **div, VALUE self, VALUE r)
/* For c = self.div(r): with round operation */
{
ENTER(5);
Real *a, *b;
U_LONG mx;
GUARD_OBJ(a,GetVpValue(self,1));
b = GetVpValue(r,0);
if(!b) return DoSomeOne(self,r,'/');
SAVE(b);
*div = b;
mx =(a->MaxPrec + b->MaxPrec + 1) * VpBaseFig();
GUARD_OBJ((*c),VpCreateRbObject(mx, "#0"));
GUARD_OBJ((*res),VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
VpDivd(*c, *res, a, b);
return (VALUE)0;
}
/* call-seq:
* div(value, digits)
* quo(value)
*
* Divide by the specified value.
*
* e.g.
* c = a.div(b,n)
*
* digits:: If specified and less than the number of significant digits of the result, the result is rounded to that number of digits, according to BigDecimal.mode.
*
* If digits is 0, the result is the same as the / operator. If not, the
* result is an integer BigDecimal, by analogy with Float#div.
*
* The alias quo is provided since div(value, 0) is the same as computing
* the quotient; see divmod.
*/
static VALUE
BigDecimal_div(VALUE self, SEL sel, VALUE r)
/* For c = self/r: with round operation */
{
ENTER(5);
Real *c=NULL, *res=NULL, *div = NULL;
r = BigDecimal_divide(&c, &res, &div, self, r);
if(r!=(VALUE)0) return r; /* coerced by other */
SAVE(c);SAVE(res);SAVE(div);
/* a/b = c + r/b */
/* c xxxxx
r 00000yyyyy ==> (y/b)*BASE >= HALF_BASE
*/
/* Round */
if(VpHasVal(div)) { /* frac[0] must be zero for NaN,INF,Zero */
VpInternalRound(c,0,c->frac[c->Prec-1],(VpBaseVal()*res->frac[0])/div->frac[0]);
}
return ToValue(c);
}
/*
* %: mod = a%b = a - (a.to_f/b).floor * b
* div = (a.to_f/b).floor
*/
static VALUE
BigDecimal_DoDivmod(VALUE self, VALUE r, Real **div, Real **mod)
{
ENTER(8);
Real *c=NULL, *d=NULL, *res=NULL;
Real *a, *b;
U_LONG mx;
GUARD_OBJ(a,GetVpValue(self,1));
b = GetVpValue(r,0);
if(!b) return DoSomeOne(self,r,rb_intern("divmod"));
SAVE(b);
if(VpIsNaN(a) || VpIsNaN(b)) goto NaN;
if(VpIsInf(a) || VpIsInf(b)) goto NaN;
if(VpIsZero(b)) goto NaN;
if(VpIsZero(a)) {
GUARD_OBJ(c,VpCreateRbObject(1, "0"));
GUARD_OBJ(d,VpCreateRbObject(1, "0"));
*div = d;
*mod = c;
return (VALUE)0;
}
mx = a->Prec;
if(mx<b->Prec) mx = b->Prec;
mx =(mx + 1) * VpBaseFig();
GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
GUARD_OBJ(res,VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
VpDivd(c, res, a, b);
mx = c->Prec *(VpBaseFig() + 1);
GUARD_OBJ(d,VpCreateRbObject(mx, "0"));
VpActiveRound(d,c,VP_ROUND_DOWN,0);
VpMult(res,d,b);
VpAddSub(c,a,res,-1);
if(!VpIsZero(c) && (VpGetSign(a)*VpGetSign(b)<0)) {
VpAddSub(res,d,VpOne(),-1);
VpAddSub(d ,c,b, 1);
*div = res;
*mod = d;
} else {
*div = d;
*mod = c;
}
return (VALUE)0;
NaN:
GUARD_OBJ(c,VpCreateRbObject(1, "NaN"));
GUARD_OBJ(d,VpCreateRbObject(1, "NaN"));
*div = d;
*mod = c;
return (VALUE)0;
}