Ruby  2.0.0p451(2014-02-24revision45167)
ext/bigdecimal/bigdecimal.c
Go to the documentation of this file.
00001 /*
00002  *
00003  * Ruby BigDecimal(Variable decimal precision) extension library.
00004  *
00005  * Copyright(C) 2002 by Shigeo Kobayashi(shigeo@tinyforest.gr.jp)
00006  *
00007  * You may distribute under the terms of either the GNU General Public
00008  * License or the Artistic License, as specified in the README file
00009  * of this BigDecimal distribution.
00010  *
00011  *  NOTE: Change log in this source removed to reduce source code size.
00012  *        See rev. 1.25 if needed.
00013  *
00014  */
00015 
00016 /* #define BIGDECIMAL_DEBUG 1 */
00017 #ifdef BIGDECIMAL_DEBUG
00018 # define BIGDECIMAL_ENABLE_VPRINT 1
00019 #endif
00020 #include "bigdecimal.h"
00021 
00022 #ifndef BIGDECIMAL_DEBUG
00023 # define NDEBUG
00024 #endif
00025 #include <assert.h>
00026 
00027 #include <ctype.h>
00028 #include <stdio.h>
00029 #include <stdlib.h>
00030 #include <string.h>
00031 #include <errno.h>
00032 #include <math.h>
00033 #include "math.h"
00034 
00035 #ifdef HAVE_IEEEFP_H
00036 #include <ieeefp.h>
00037 #endif
00038 
00039 /* #define ENABLE_NUMERIC_STRING */
00040 
00041 VALUE rb_cBigDecimal;
00042 VALUE rb_mBigMath;
00043 
00044 static ID id_BigDecimal_exception_mode;
00045 static ID id_BigDecimal_rounding_mode;
00046 static ID id_BigDecimal_precision_limit;
00047 
00048 static ID id_up;
00049 static ID id_down;
00050 static ID id_truncate;
00051 static ID id_half_up;
00052 static ID id_default;
00053 static ID id_half_down;
00054 static ID id_half_even;
00055 static ID id_banker;
00056 static ID id_ceiling;
00057 static ID id_ceil;
00058 static ID id_floor;
00059 static ID id_to_r;
00060 static ID id_eq;
00061 
00062 /* MACRO's to guard objects from GC by keeping them in stack */
00063 #define ENTER(n) volatile VALUE RB_UNUSED_VAR(vStack[n]);int iStack=0
00064 #define PUSH(x)  vStack[iStack++] = (VALUE)(x);
00065 #define SAVE(p)  PUSH(p->obj);
00066 #define GUARD_OBJ(p,y) {p=y;SAVE(p);}
00067 
00068 #define BASE_FIG  RMPD_COMPONENT_FIGURES
00069 #define BASE      RMPD_BASE
00070 
00071 #define HALF_BASE (BASE/2)
00072 #define BASE1 (BASE/10)
00073 
00074 #ifndef DBLE_FIG
00075 #define DBLE_FIG (DBL_DIG+1)    /* figure of double */
00076 #endif
00077 
00078 #ifndef RBIGNUM_ZERO_P
00079 # define RBIGNUM_ZERO_P(x) (RBIGNUM_LEN(x) == 0 || \
00080                             (RBIGNUM_DIGITS(x)[0] == 0 && \
00081                              (RBIGNUM_LEN(x) == 1 || bigzero_p(x))))
00082 #endif
00083 
00084 static inline int
00085 bigzero_p(VALUE x)
00086 {
00087     long i;
00088     BDIGIT *ds = RBIGNUM_DIGITS(x);
00089 
00090     for (i = RBIGNUM_LEN(x) - 1; 0 <= i; i--) {
00091         if (ds[i]) return 0;
00092     }
00093     return 1;
00094 }
00095 
00096 #ifndef RRATIONAL_ZERO_P
00097 # define RRATIONAL_ZERO_P(x) (FIXNUM_P(RRATIONAL(x)->num) && \
00098                               FIX2LONG(RRATIONAL(x)->num) == 0)
00099 #endif
00100 
00101 #ifndef RRATIONAL_NEGATIVE_P
00102 # define RRATIONAL_NEGATIVE_P(x) RTEST(rb_funcall((x), '<', 1, INT2FIX(0)))
00103 #endif
00104 
00105 #ifndef DECIMAL_SIZE_OF_BITS
00106 #define DECIMAL_SIZE_OF_BITS(n) (((n) * 3010 + 9998) / 9999)
00107 /* an approximation of ceil(n * log10(2)), upto 65536 at least */
00108 #endif
00109 
00110 #ifdef PRIsVALUE
00111 # define RB_OBJ_CLASSNAME(obj) rb_obj_class(obj)
00112 # define RB_OBJ_STRING(obj) (obj)
00113 #else
00114 # define PRIsVALUE "s"
00115 # define RB_OBJ_CLASSNAME(obj) rb_obj_classname(obj)
00116 # define RB_OBJ_STRING(obj) StringValueCStr(obj)
00117 #endif
00118 
00119 /*
00120  * ================== Ruby Interface part ==========================
00121  */
00122 #define DoSomeOne(x,y,f) rb_num_coerce_bin(x,y,f)
00123 
00124 /*
00125  * Returns the BigDecimal version number.
00126  */
00127 static VALUE
00128 BigDecimal_version(VALUE self)
00129 {
00130     /*
00131      * 1.0.0: Ruby 1.8.0
00132      * 1.0.1: Ruby 1.8.1
00133      * 1.1.0: Ruby 1.9.3
00134     */
00135     return rb_str_new2("1.1.0");
00136 }
00137 
00138 /*
00139  *   VP routines used in BigDecimal part
00140  */
00141 static unsigned short VpGetException(void);
00142 static void  VpSetException(unsigned short f);
00143 static void  VpInternalRound(Real *c, size_t ixDigit, BDIGIT vPrev, BDIGIT v);
00144 static int   VpLimitRound(Real *c, size_t ixDigit);
00145 static Real *VpCopy(Real *pv, Real const* const x);
00146 
00147 /*
00148  *  **** BigDecimal part ****
00149  */
00150 
00151 static void
00152 BigDecimal_delete(void *pv)
00153 {
00154     VpFree(pv);
00155 }
00156 
00157 static size_t
00158 BigDecimal_memsize(const void *ptr)
00159 {
00160     const Real *pv = ptr;
00161     return pv ? (sizeof(*pv) + pv->MaxPrec * sizeof(BDIGIT)) : 0;
00162 }
00163 
00164 static const rb_data_type_t BigDecimal_data_type = {
00165     "BigDecimal",
00166     {0, BigDecimal_delete, BigDecimal_memsize,},
00167 };
00168 
00169 static inline int
00170 is_kind_of_BigDecimal(VALUE const v)
00171 {
00172     return rb_typeddata_is_kind_of(v, &BigDecimal_data_type);
00173 }
00174 
00175 static VALUE
00176 ToValue(Real *p)
00177 {
00178     if(VpIsNaN(p)) {
00179         VpException(VP_EXCEPTION_NaN,"Computation results to 'NaN'(Not a Number)",0);
00180     } else if(VpIsPosInf(p)) {
00181         VpException(VP_EXCEPTION_INFINITY,"Computation results to 'Infinity'",0);
00182     } else if(VpIsNegInf(p)) {
00183         VpException(VP_EXCEPTION_INFINITY,"Computation results to '-Infinity'",0);
00184     }
00185     return p->obj;
00186 }
00187 
00188 NORETURN(static void cannot_be_coerced_into_BigDecimal(VALUE, VALUE));
00189 
00190 static void
00191 cannot_be_coerced_into_BigDecimal(VALUE exc_class, VALUE v)
00192 {
00193     VALUE str;
00194 
00195     if (rb_special_const_p(v)) {
00196         str = rb_inspect(v);
00197     }
00198     else {
00199         str = rb_class_name(rb_obj_class(v));
00200     }
00201 
00202     str = rb_str_cat2(rb_str_dup(str), " can't be coerced into BigDecimal");
00203     rb_exc_raise(rb_exc_new3(exc_class, str));
00204 }
00205 
00206 static VALUE BigDecimal_div2(int, VALUE*, VALUE);
00207 
00208 static Real*
00209 GetVpValueWithPrec(VALUE v, long prec, int must)
00210 {
00211     Real *pv;
00212     VALUE num, bg, args[2];
00213     char szD[128];
00214     VALUE orig = Qundef;
00215 
00216 again:
00217     switch(TYPE(v))
00218     {
00219       case T_FLOAT:
00220         if (prec < 0) goto unable_to_coerce_without_prec;
00221         if (prec > DBL_DIG+1)goto SomeOneMayDoIt;
00222         v = rb_funcall(v, id_to_r, 0);
00223         goto again;
00224       case T_RATIONAL:
00225         if (prec < 0) goto unable_to_coerce_without_prec;
00226 
00227         if (orig == Qundef ? (orig = v, 1) : orig != v) {
00228             num = RRATIONAL(v)->num;
00229             pv = GetVpValueWithPrec(num, -1, must);
00230             if (pv == NULL) goto SomeOneMayDoIt;
00231 
00232             args[0] = RRATIONAL(v)->den;
00233             args[1] = LONG2NUM(prec);
00234             v = BigDecimal_div2(2, args, ToValue(pv));
00235             goto again;
00236         }
00237 
00238         v = orig;
00239         goto SomeOneMayDoIt;
00240 
00241       case T_DATA:
00242         if (is_kind_of_BigDecimal(v)) {
00243             pv = DATA_PTR(v);
00244             return pv;
00245         }
00246         else {
00247             goto SomeOneMayDoIt;
00248         }
00249         break;
00250 
00251       case T_FIXNUM:
00252         sprintf(szD, "%ld", FIX2LONG(v));
00253         return VpCreateRbObject(VpBaseFig() * 2 + 1, szD);
00254 
00255 #ifdef ENABLE_NUMERIC_STRING
00256       case T_STRING:
00257         SafeStringValue(v);
00258         return VpCreateRbObject(strlen(RSTRING_PTR(v)) + VpBaseFig() + 1,
00259                                 RSTRING_PTR(v));
00260 #endif /* ENABLE_NUMERIC_STRING */
00261 
00262       case T_BIGNUM:
00263         bg = rb_big2str(v, 10);
00264         return VpCreateRbObject(strlen(RSTRING_PTR(bg)) + VpBaseFig() + 1,
00265                                 RSTRING_PTR(bg));
00266       default:
00267         goto SomeOneMayDoIt;
00268     }
00269 
00270 SomeOneMayDoIt:
00271     if (must) {
00272         cannot_be_coerced_into_BigDecimal(rb_eTypeError, v);
00273     }
00274     return NULL; /* NULL means to coerce */
00275 
00276 unable_to_coerce_without_prec:
00277     if (must) {
00278         rb_raise(rb_eArgError,
00279                  "%"PRIsVALUE" can't be coerced into BigDecimal without a precision",
00280                  RB_OBJ_CLASSNAME(v));
00281     }
00282     return NULL;
00283 }
00284 
00285 static Real*
00286 GetVpValue(VALUE v, int must)
00287 {
00288     return GetVpValueWithPrec(v, -1, must);
00289 }
00290 
00291 /* call-seq:
00292  * BigDecimal.double_fig
00293  *
00294  * The BigDecimal.double_fig class method returns the number of digits a
00295  * Float number is allowed to have. The result depends upon the CPU and OS
00296  * in use.
00297  */
00298 static VALUE
00299 BigDecimal_double_fig(VALUE self)
00300 {
00301     return INT2FIX(VpDblFig());
00302 }
00303 
00304 /* call-seq:
00305  * precs
00306  *
00307  * Returns an Array of two Integer values.
00308  *
00309  * The first value is the current number of significant digits in the
00310  * BigDecimal. The second value is the maximum number of significant digits
00311  * for the BigDecimal.
00312  */
00313 static VALUE
00314 BigDecimal_prec(VALUE self)
00315 {
00316     ENTER(1);
00317     Real *p;
00318     VALUE obj;
00319 
00320     GUARD_OBJ(p,GetVpValue(self,1));
00321     obj = rb_assoc_new(INT2NUM(p->Prec*VpBaseFig()),
00322                        INT2NUM(p->MaxPrec*VpBaseFig()));
00323     return obj;
00324 }
00325 
00326 /*
00327  * call-seq: hash
00328  *
00329  * Creates a hash for this BigDecimal.
00330  *
00331  * Two BigDecimals with equal sign,
00332  * fractional part and exponent have the same hash.
00333  */
00334 static VALUE
00335 BigDecimal_hash(VALUE self)
00336 {
00337     ENTER(1);
00338     Real *p;
00339     st_index_t hash;
00340 
00341     GUARD_OBJ(p,GetVpValue(self,1));
00342     hash = (st_index_t)p->sign;
00343     /* hash!=2: the case for 0(1),NaN(0) or +-Infinity(3) is sign itself */
00344     if(hash == 2 || hash == (st_index_t)-2) {
00345         hash ^= rb_memhash(p->frac, sizeof(BDIGIT)*p->Prec);
00346         hash += p->exponent;
00347     }
00348     return INT2FIX(hash);
00349 }
00350 
00351 /*
00352  * call-seq: _dump
00353  *
00354  * Method used to provide marshalling support.
00355  *
00356  *      inf = BigDecimal.new('Infinity')
00357  *      => #<BigDecimal:1e16fa8,'Infinity',9(9)>
00358  *      BigDecimal._load(inf._dump)
00359  *      => #<BigDecimal:1df8dc8,'Infinity',9(9)>
00360  *
00361  * See the Marshal module.
00362  */
00363 static VALUE
00364 BigDecimal_dump(int argc, VALUE *argv, VALUE self)
00365 {
00366     ENTER(5);
00367     Real *vp;
00368     char *psz;
00369     VALUE dummy;
00370     volatile VALUE dump;
00371 
00372     rb_scan_args(argc, argv, "01", &dummy);
00373     GUARD_OBJ(vp,GetVpValue(self,1));
00374     dump = rb_str_new(0,VpNumOfChars(vp,"E")+50);
00375     psz = RSTRING_PTR(dump);
00376     sprintf(psz, "%"PRIuSIZE":", VpMaxPrec(vp)*VpBaseFig());
00377     VpToString(vp, psz+strlen(psz), 0, 0);
00378     rb_str_resize(dump, strlen(psz));
00379     return dump;
00380 }
00381 
00382 /*
00383  * Internal method used to provide marshalling support. See the Marshal module.
00384  */
00385 static VALUE
00386 BigDecimal_load(VALUE self, VALUE str)
00387 {
00388     ENTER(2);
00389     Real *pv;
00390     unsigned char *pch;
00391     unsigned char ch;
00392     unsigned long m=0;
00393 
00394     SafeStringValue(str);
00395     pch = (unsigned char *)RSTRING_PTR(str);
00396     /* First get max prec */
00397     while((*pch)!=(unsigned char)'\0' && (ch=*pch++)!=(unsigned char)':') {
00398         if(!ISDIGIT(ch)) {
00399             rb_raise(rb_eTypeError, "load failed: invalid character in the marshaled string");
00400         }
00401         m = m*10 + (unsigned long)(ch-'0');
00402     }
00403     if(m>VpBaseFig()) m -= VpBaseFig();
00404     GUARD_OBJ(pv,VpNewRbClass(m,(char *)pch,self));
00405     m /= VpBaseFig();
00406     if(m && pv->MaxPrec>m) pv->MaxPrec = m+1;
00407     return ToValue(pv);
00408 }
00409 
00410 static unsigned short
00411 check_rounding_mode(VALUE const v)
00412 {
00413     unsigned short sw;
00414     ID id;
00415     switch (TYPE(v)) {
00416       case T_SYMBOL:
00417         id = SYM2ID(v);
00418         if (id == id_up)
00419             return VP_ROUND_UP;
00420         if (id == id_down || id == id_truncate)
00421             return VP_ROUND_DOWN;
00422         if (id == id_half_up || id == id_default)
00423             return VP_ROUND_HALF_UP;
00424         if (id == id_half_down)
00425             return VP_ROUND_HALF_DOWN;
00426         if (id == id_half_even || id == id_banker)
00427             return VP_ROUND_HALF_EVEN;
00428         if (id == id_ceiling || id == id_ceil)
00429             return VP_ROUND_CEIL;
00430         if (id == id_floor)
00431             return VP_ROUND_FLOOR;
00432         rb_raise(rb_eArgError, "invalid rounding mode");
00433 
00434       default:
00435         break;
00436     }
00437 
00438     Check_Type(v, T_FIXNUM);
00439     sw = (unsigned short)FIX2UINT(v);
00440     if (!VpIsRoundMode(sw)) {
00441         rb_raise(rb_eArgError, "invalid rounding mode");
00442     }
00443     return sw;
00444 }
00445 
00446 /* call-seq:
00447  * BigDecimal.mode(mode, value)
00448  *
00449  * Controls handling of arithmetic exceptions and rounding. If no value
00450  * is supplied, the current value is returned.
00451  *
00452  * Six values of the mode parameter control the handling of arithmetic
00453  * exceptions:
00454  *
00455  * BigDecimal::EXCEPTION_NaN
00456  * BigDecimal::EXCEPTION_INFINITY
00457  * BigDecimal::EXCEPTION_UNDERFLOW
00458  * BigDecimal::EXCEPTION_OVERFLOW
00459  * BigDecimal::EXCEPTION_ZERODIVIDE
00460  * BigDecimal::EXCEPTION_ALL
00461  *
00462  * For each mode parameter above, if the value set is false, computation
00463  * continues after an arithmetic exception of the appropriate type.
00464  * When computation continues, results are as follows:
00465  *
00466  * EXCEPTION_NaN:: NaN
00467  * EXCEPTION_INFINITY:: +infinity or -infinity
00468  * EXCEPTION_UNDERFLOW:: 0
00469  * EXCEPTION_OVERFLOW:: +infinity or -infinity
00470  * EXCEPTION_ZERODIVIDE:: +infinity or -infinity
00471  *
00472  * One value of the mode parameter controls the rounding of numeric values:
00473  * BigDecimal::ROUND_MODE. The values it can take are:
00474  *
00475  * ROUND_UP, :up:: round away from zero
00476  * ROUND_DOWN, :down, :truncate:: round towards zero (truncate)
00477  * ROUND_HALF_UP, :half_up, :default:: round towards the nearest neighbor, unless both neighbors are equidistant, in which case round away from zero. (default)
00478  * ROUND_HALF_DOWN, :half_down:: round towards the nearest neighbor, unless both neighbors are equidistant, in which case round towards zero.
00479  * ROUND_HALF_EVEN, :half_even, :banker:: round towards the nearest neighbor, unless both neighbors are equidistant, in which case round towards the even neighbor (Banker's rounding)
00480  * ROUND_CEILING, :ceiling, :ceil:: round towards positive infinity (ceil)
00481  * ROUND_FLOOR, :floor:: round towards negative infinity (floor)
00482  *
00483  */
00484 static VALUE
00485 BigDecimal_mode(int argc, VALUE *argv, VALUE self)
00486 {
00487     VALUE which;
00488     VALUE val;
00489     unsigned long f,fo;
00490 
00491     if(rb_scan_args(argc,argv,"11",&which,&val)==1) val = Qnil;
00492 
00493     Check_Type(which, T_FIXNUM);
00494     f = (unsigned long)FIX2INT(which);
00495 
00496     if(f&VP_EXCEPTION_ALL) {
00497         /* Exception mode setting */
00498         fo = VpGetException();
00499         if(val==Qnil) return INT2FIX(fo);
00500         if(val!=Qfalse && val!=Qtrue) {
00501             rb_raise(rb_eArgError, "second argument must be true or false");
00502             return Qnil; /* Not reached */
00503         }
00504         if(f&VP_EXCEPTION_INFINITY) {
00505             VpSetException((unsigned short)((val==Qtrue)?(fo|VP_EXCEPTION_INFINITY):
00506                            (fo&(~VP_EXCEPTION_INFINITY))));
00507         }
00508         fo = VpGetException();
00509         if(f&VP_EXCEPTION_NaN) {
00510             VpSetException((unsigned short)((val==Qtrue)?(fo|VP_EXCEPTION_NaN):
00511                            (fo&(~VP_EXCEPTION_NaN))));
00512         }
00513         fo = VpGetException();
00514         if(f&VP_EXCEPTION_UNDERFLOW) {
00515             VpSetException((unsigned short)((val==Qtrue)?(fo|VP_EXCEPTION_UNDERFLOW):
00516                            (fo&(~VP_EXCEPTION_UNDERFLOW))));
00517         }
00518         fo = VpGetException();
00519         if(f&VP_EXCEPTION_ZERODIVIDE) {
00520             VpSetException((unsigned short)((val==Qtrue)?(fo|VP_EXCEPTION_ZERODIVIDE):
00521                            (fo&(~VP_EXCEPTION_ZERODIVIDE))));
00522         }
00523         fo = VpGetException();
00524         return INT2FIX(fo);
00525     }
00526     if (VP_ROUND_MODE == f) {
00527         /* Rounding mode setting */
00528         unsigned short sw;
00529         fo = VpGetRoundMode();
00530         if (NIL_P(val)) return INT2FIX(fo);
00531         sw = check_rounding_mode(val);
00532         fo = VpSetRoundMode(sw);
00533         return INT2FIX(fo);
00534     }
00535     rb_raise(rb_eTypeError, "first argument for BigDecimal#mode invalid");
00536     return Qnil;
00537 }
00538 
00539 static size_t
00540 GetAddSubPrec(Real *a, Real *b)
00541 {
00542     size_t mxs;
00543     size_t mx = a->Prec;
00544     SIGNED_VALUE d;
00545 
00546     if(!VpIsDef(a) || !VpIsDef(b)) return (size_t)-1L;
00547     if(mx < b->Prec) mx = b->Prec;
00548     if(a->exponent!=b->exponent) {
00549         mxs = mx;
00550         d = a->exponent - b->exponent;
00551         if (d < 0) d = -d;
00552         mx = mx + (size_t)d;
00553         if (mx<mxs) {
00554             return VpException(VP_EXCEPTION_INFINITY,"Exponent overflow",0);
00555         }
00556     }
00557     return mx;
00558 }
00559 
00560 static SIGNED_VALUE
00561 GetPositiveInt(VALUE v)
00562 {
00563     SIGNED_VALUE n;
00564     Check_Type(v, T_FIXNUM);
00565     n = FIX2INT(v);
00566     if (n < 0) {
00567         rb_raise(rb_eArgError, "argument must be positive");
00568     }
00569     return n;
00570 }
00571 
00572 VP_EXPORT Real *
00573 VpNewRbClass(size_t mx, const char *str, VALUE klass)
00574 {
00575     Real *pv = VpAlloc(mx,str);
00576     pv->obj = TypedData_Wrap_Struct(klass, &BigDecimal_data_type, pv);
00577     return pv;
00578 }
00579 
00580 VP_EXPORT Real *
00581 VpCreateRbObject(size_t mx, const char *str)
00582 {
00583     Real *pv = VpAlloc(mx,str);
00584     pv->obj = TypedData_Wrap_Struct(rb_cBigDecimal, &BigDecimal_data_type, pv);
00585     return pv;
00586 }
00587 
00588 #define VpAllocReal(prec) (Real *)VpMemAlloc(offsetof(Real, frac) + (prec) * sizeof(BDIGIT))
00589 #define VpReallocReal(ptr, prec) (Real *)VpMemRealloc((ptr), offsetof(Real, frac) + (prec) * sizeof(BDIGIT))
00590 
00591 static Real *
00592 VpCopy(Real *pv, Real const* const x)
00593 {
00594     assert(x != NULL);
00595 
00596     pv = VpReallocReal(pv, x->MaxPrec);
00597     pv->MaxPrec = x->MaxPrec;
00598     pv->Prec = x->Prec;
00599     pv->exponent = x->exponent;
00600     pv->sign = x->sign;
00601     pv->flag = x->flag;
00602     MEMCPY(pv->frac, x->frac, BDIGIT, pv->MaxPrec);
00603 
00604     return pv;
00605 }
00606 
00607 /* Returns True if the value is Not a Number */
00608 static VALUE
00609 BigDecimal_IsNaN(VALUE self)
00610 {
00611     Real *p = GetVpValue(self,1);
00612     if(VpIsNaN(p))  return Qtrue;
00613     return Qfalse;
00614 }
00615 
00616 /* Returns nil, -1, or +1 depending on whether the value is finite,
00617  * -infinity, or +infinity.
00618  */
00619 static VALUE
00620 BigDecimal_IsInfinite(VALUE self)
00621 {
00622     Real *p = GetVpValue(self,1);
00623     if(VpIsPosInf(p)) return INT2FIX(1);
00624     if(VpIsNegInf(p)) return INT2FIX(-1);
00625     return Qnil;
00626 }
00627 
00628 /* Returns True if the value is finite (not NaN or infinite) */
00629 static VALUE
00630 BigDecimal_IsFinite(VALUE self)
00631 {
00632     Real *p = GetVpValue(self,1);
00633     if(VpIsNaN(p)) return Qfalse;
00634     if(VpIsInf(p)) return Qfalse;
00635     return Qtrue;
00636 }
00637 
00638 static void
00639 BigDecimal_check_num(Real *p)
00640 {
00641     if(VpIsNaN(p)) {
00642        VpException(VP_EXCEPTION_NaN,"Computation results to 'NaN'(Not a Number)",1);
00643     } else if(VpIsPosInf(p)) {
00644        VpException(VP_EXCEPTION_INFINITY,"Computation results to 'Infinity'",1);
00645     } else if(VpIsNegInf(p)) {
00646        VpException(VP_EXCEPTION_INFINITY,"Computation results to '-Infinity'",1);
00647     }
00648 }
00649 
00650 static VALUE BigDecimal_split(VALUE self);
00651 
00652 /* Returns the value as an integer (Fixnum or Bignum).
00653  *
00654  * If the BigNumber is infinity or NaN, raises FloatDomainError.
00655  */
00656 static VALUE
00657 BigDecimal_to_i(VALUE self)
00658 {
00659     ENTER(5);
00660     ssize_t e, nf;
00661     Real *p;
00662 
00663     GUARD_OBJ(p,GetVpValue(self,1));
00664     BigDecimal_check_num(p);
00665 
00666     e = VpExponent10(p);
00667     if(e<=0) return INT2FIX(0);
00668     nf = VpBaseFig();
00669     if(e<=nf) {
00670         return LONG2NUM((long)(VpGetSign(p)*(BDIGIT_DBL_SIGNED)p->frac[0]));
00671     }
00672     else {
00673         VALUE a = BigDecimal_split(self);
00674         VALUE digits = RARRAY_PTR(a)[1];
00675         VALUE numerator = rb_funcall(digits, rb_intern("to_i"), 0);
00676         VALUE ret;
00677         ssize_t dpower = e - (ssize_t)RSTRING_LEN(digits);
00678 
00679         if (VpGetSign(p) < 0) {
00680             numerator = rb_funcall(numerator, '*', 1, INT2FIX(-1));
00681         }
00682         if (dpower < 0) {
00683             ret = rb_funcall(numerator, rb_intern("div"), 1,
00684                               rb_funcall(INT2FIX(10), rb_intern("**"), 1,
00685                                          INT2FIX(-dpower)));
00686         }
00687         else
00688             ret = rb_funcall(numerator, '*', 1,
00689                              rb_funcall(INT2FIX(10), rb_intern("**"), 1,
00690                                         INT2FIX(dpower)));
00691         if (RB_TYPE_P(ret, T_FLOAT))
00692             rb_raise(rb_eFloatDomainError, "Infinity");
00693         return ret;
00694     }
00695 }
00696 
00697 /* Returns a new Float object having approximately the same value as the
00698  * BigDecimal number. Normal accuracy limits and built-in errors of binary
00699  * Float arithmetic apply.
00700  */
00701 static VALUE
00702 BigDecimal_to_f(VALUE self)
00703 {
00704     ENTER(1);
00705     Real *p;
00706     double d;
00707     SIGNED_VALUE e;
00708     char *buf;
00709     volatile VALUE str;
00710 
00711     GUARD_OBJ(p, GetVpValue(self, 1));
00712     if (VpVtoD(&d, &e, p) != 1)
00713         return rb_float_new(d);
00714     if (e > (SIGNED_VALUE)(DBL_MAX_10_EXP+BASE_FIG))
00715         goto overflow;
00716     if (e < (SIGNED_VALUE)(DBL_MIN_10_EXP-BASE_FIG))
00717         goto underflow;
00718 
00719     str = rb_str_new(0, VpNumOfChars(p,"E"));
00720     buf = RSTRING_PTR(str);
00721     VpToString(p, buf, 0, 0);
00722     errno = 0;
00723     d = strtod(buf, 0);
00724     if (errno == ERANGE) {
00725         if (d == 0.0) goto underflow;
00726         if (fabs(d) >= HUGE_VAL) goto overflow;
00727     }
00728     return rb_float_new(d);
00729 
00730 overflow:
00731     VpException(VP_EXCEPTION_OVERFLOW, "BigDecimal to Float conversion", 0);
00732     if (p->sign >= 0)
00733         return rb_float_new(VpGetDoublePosInf());
00734     else
00735         return rb_float_new(VpGetDoubleNegInf());
00736 
00737 underflow:
00738     VpException(VP_EXCEPTION_UNDERFLOW, "BigDecimal to Float conversion", 0);
00739     if (p->sign >= 0)
00740         return rb_float_new(0.0);
00741     else
00742         return rb_float_new(-0.0);
00743 }
00744 
00745 
00746 /* Converts a BigDecimal to a Rational.
00747  */
00748 static VALUE
00749 BigDecimal_to_r(VALUE self)
00750 {
00751     Real *p;
00752     ssize_t sign, power, denomi_power;
00753     VALUE a, digits, numerator;
00754 
00755     p = GetVpValue(self,1);
00756     BigDecimal_check_num(p);
00757 
00758     sign = VpGetSign(p);
00759     power = VpExponent10(p);
00760     a = BigDecimal_split(self);
00761     digits = RARRAY_PTR(a)[1];
00762     denomi_power = power - RSTRING_LEN(digits);
00763     numerator = rb_funcall(digits, rb_intern("to_i"), 0);
00764 
00765     if (sign < 0) {
00766         numerator = rb_funcall(numerator, '*', 1, INT2FIX(-1));
00767     }
00768     if (denomi_power < 0) {
00769         return rb_Rational(numerator,
00770                            rb_funcall(INT2FIX(10), rb_intern("**"), 1,
00771                                       INT2FIX(-denomi_power)));
00772     }
00773     else {
00774         return rb_Rational1(rb_funcall(numerator, '*', 1,
00775                                        rb_funcall(INT2FIX(10), rb_intern("**"), 1,
00776                                                   INT2FIX(denomi_power))));
00777     }
00778 }
00779 
00780 /* The coerce method provides support for Ruby type coercion. It is not
00781  * enabled by default.
00782  *
00783  * This means that binary operations like + * / or - can often be performed
00784  * on a BigDecimal and an object of another type, if the other object can
00785  * be coerced into a BigDecimal value.
00786  *
00787  * e.g.
00788  * a = BigDecimal.new("1.0")
00789  * b = a / 2.0  -> 0.5
00790  *
00791  * Note that coercing a String to a BigDecimal is not supported by default;
00792  * it requires a special compile-time option when building Ruby.
00793  */
00794 static VALUE
00795 BigDecimal_coerce(VALUE self, VALUE other)
00796 {
00797     ENTER(2);
00798     VALUE obj;
00799     Real *b;
00800 
00801     if (RB_TYPE_P(other, T_FLOAT)) {
00802         obj = rb_assoc_new(other, BigDecimal_to_f(self));
00803     }
00804     else {
00805         if (RB_TYPE_P(other, T_RATIONAL)) {
00806             Real* pv = DATA_PTR(self);
00807             GUARD_OBJ(b, GetVpValueWithPrec(other, pv->Prec*VpBaseFig(), 1));
00808         }
00809         else {
00810             GUARD_OBJ(b, GetVpValue(other, 1));
00811         }
00812         obj = rb_assoc_new(b->obj, self);
00813     }
00814 
00815     return obj;
00816 }
00817 
00818 /*
00819  * call-seq: +@
00820  *
00821  * Return self.
00822  *
00823  * e.g.
00824  *   b = +a  # b == a
00825  */
00826 static VALUE
00827 BigDecimal_uplus(VALUE self)
00828 {
00829     return self;
00830 }
00831 
00832  /*
00833   * Document-method: BigDecimal#add
00834   * Document-method: BigDecimal#+
00835   *
00836   * call-seq:
00837   * add(value, digits)
00838   *
00839   * Add the specified value.
00840   *
00841   * e.g.
00842   *   c = a.add(b,n)
00843   *   c = a + b
00844   *
00845   * digits:: If specified and less than the number of significant digits of the
00846   * result, the result is rounded to that number of digits, according to
00847   * BigDecimal.mode.
00848   */
00849 static VALUE
00850 BigDecimal_add(VALUE self, VALUE r)
00851 {
00852     ENTER(5);
00853     Real *c, *a, *b;
00854     size_t mx;
00855 
00856     GUARD_OBJ(a, GetVpValue(self, 1));
00857     if (RB_TYPE_P(r, T_FLOAT)) {
00858         b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
00859     }
00860     else if (RB_TYPE_P(r, T_RATIONAL)) {
00861         b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
00862     }
00863     else {
00864         b = GetVpValue(r,0);
00865     }
00866 
00867     if (!b) return DoSomeOne(self,r,'+');
00868     SAVE(b);
00869 
00870     if (VpIsNaN(b)) return b->obj;
00871     if (VpIsNaN(a)) return a->obj;
00872 
00873     mx = GetAddSubPrec(a, b);
00874     if (mx == (size_t)-1L) {
00875         GUARD_OBJ(c,VpCreateRbObject(VpBaseFig() + 1, "0"));
00876         VpAddSub(c, a, b, 1);
00877     }
00878     else {
00879         GUARD_OBJ(c, VpCreateRbObject(mx * (VpBaseFig() + 1), "0"));
00880         if(!mx) {
00881             VpSetInf(c, VpGetSign(a));
00882         }
00883         else {
00884             VpAddSub(c, a, b, 1);
00885         }
00886     }
00887     return ToValue(c);
00888 }
00889 
00890  /* call-seq:
00891   * sub(value, digits)
00892   *
00893   * Subtract the specified value.
00894   *
00895   * e.g.
00896   *   c = a.sub(b,n)
00897   *   c = a - b
00898   *
00899   * digits:: If specified and less than the number of significant digits of the
00900   * result, the result is rounded to that number of digits, according to
00901   * BigDecimal.mode.
00902   */
00903 static VALUE
00904 BigDecimal_sub(VALUE self, VALUE r)
00905 {
00906     ENTER(5);
00907     Real *c, *a, *b;
00908     size_t mx;
00909 
00910     GUARD_OBJ(a,GetVpValue(self,1));
00911     if (RB_TYPE_P(r, T_FLOAT)) {
00912         b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
00913     }
00914     else if (RB_TYPE_P(r, T_RATIONAL)) {
00915         b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
00916     }
00917     else {
00918         b = GetVpValue(r,0);
00919     }
00920 
00921     if(!b) return DoSomeOne(self,r,'-');
00922     SAVE(b);
00923 
00924     if(VpIsNaN(b)) return b->obj;
00925     if(VpIsNaN(a)) return a->obj;
00926 
00927     mx = GetAddSubPrec(a,b);
00928     if (mx == (size_t)-1L) {
00929         GUARD_OBJ(c,VpCreateRbObject(VpBaseFig() + 1, "0"));
00930         VpAddSub(c, a, b, -1);
00931     } else {
00932         GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0"));
00933         if(!mx) {
00934             VpSetInf(c,VpGetSign(a));
00935         } else {
00936             VpAddSub(c, a, b, -1);
00937         }
00938     }
00939     return ToValue(c);
00940 }
00941 
00942 static VALUE
00943 BigDecimalCmp(VALUE self, VALUE r,char op)
00944 {
00945     ENTER(5);
00946     SIGNED_VALUE e;
00947     Real *a, *b=0;
00948     GUARD_OBJ(a,GetVpValue(self,1));
00949     switch (TYPE(r)) {
00950     case T_DATA:
00951         if (!is_kind_of_BigDecimal(r)) break;
00952         /* fall through */
00953     case T_FIXNUM:
00954         /* fall through */
00955     case T_BIGNUM:
00956         GUARD_OBJ(b, GetVpValue(r,0));
00957         break;
00958 
00959     case T_FLOAT:
00960         GUARD_OBJ(b, GetVpValueWithPrec(r, DBL_DIG+1, 0));
00961         break;
00962 
00963     case T_RATIONAL:
00964         GUARD_OBJ(b, GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 0));
00965         break;
00966 
00967     default:
00968         break;
00969     }
00970     if (b == NULL) {
00971         ID f = 0;
00972 
00973         switch (op) {
00974         case '*':
00975             return rb_num_coerce_cmp(self, r, rb_intern("<=>"));
00976 
00977         case '=':
00978             return RTEST(rb_num_coerce_cmp(self, r, rb_intern("=="))) ? Qtrue : Qfalse;
00979 
00980         case 'G':
00981             f = rb_intern(">=");
00982             break;
00983 
00984         case 'L':
00985             f = rb_intern("<=");
00986             break;
00987 
00988         case '>':
00989             /* fall through */
00990         case '<':
00991             f = (ID)op;
00992             break;
00993 
00994         default:
00995             break;
00996         }
00997         return rb_num_coerce_relop(self, r, f);
00998     }
00999     SAVE(b);
01000     e = VpComp(a, b);
01001     if (e == 999)
01002         return (op == '*') ? Qnil : Qfalse;
01003     switch (op) {
01004     case '*':
01005         return   INT2FIX(e); /* any op */
01006 
01007     case '=':
01008         if(e==0) return Qtrue;
01009         return Qfalse;
01010 
01011     case 'G':
01012         if(e>=0) return Qtrue;
01013         return Qfalse;
01014 
01015     case '>':
01016         if(e> 0) return Qtrue;
01017         return Qfalse;
01018 
01019     case 'L':
01020         if(e<=0) return Qtrue;
01021         return Qfalse;
01022 
01023     case '<':
01024         if(e< 0) return Qtrue;
01025         return Qfalse;
01026 
01027     default:
01028         break;
01029     }
01030 
01031     rb_bug("Undefined operation in BigDecimalCmp()");
01032 
01033     UNREACHABLE;
01034 }
01035 
01036 /* Returns True if the value is zero. */
01037 static VALUE
01038 BigDecimal_zero(VALUE self)
01039 {
01040     Real *a = GetVpValue(self,1);
01041     return VpIsZero(a) ? Qtrue : Qfalse;
01042 }
01043 
01044 /* Returns self if the value is non-zero, nil otherwise. */
01045 static VALUE
01046 BigDecimal_nonzero(VALUE self)
01047 {
01048     Real *a = GetVpValue(self,1);
01049     return VpIsZero(a) ? Qnil : self;
01050 }
01051 
01052 /* The comparison operator.
01053  * a <=> b is 0 if a == b, 1 if a > b, -1 if a < b.
01054  */
01055 static VALUE
01056 BigDecimal_comp(VALUE self, VALUE r)
01057 {
01058     return BigDecimalCmp(self, r, '*');
01059 }
01060 
01061 /*
01062  * Tests for value equality; returns true if the values are equal.
01063  *
01064  * The == and === operators and the eql? method have the same implementation
01065  * for BigDecimal.
01066  *
01067  * Values may be coerced to perform the comparison:
01068  *
01069  * BigDecimal.new('1.0') == 1.0  -> true
01070  */
01071 static VALUE
01072 BigDecimal_eq(VALUE self, VALUE r)
01073 {
01074     return BigDecimalCmp(self, r, '=');
01075 }
01076 
01077 /* call-seq:
01078  * a < b
01079  *
01080  * Returns true if a is less than b.
01081  *
01082  * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce).
01083  */
01084 static VALUE
01085 BigDecimal_lt(VALUE self, VALUE r)
01086 {
01087     return BigDecimalCmp(self, r, '<');
01088 }
01089 
01090 /* call-seq:
01091  * a <= b
01092  *
01093  * Returns true if a is less than or equal to b.
01094  *
01095  * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce).
01096  */
01097 static VALUE
01098 BigDecimal_le(VALUE self, VALUE r)
01099 {
01100     return BigDecimalCmp(self, r, 'L');
01101 }
01102 
01103 /* call-seq:
01104  * a > b
01105  *
01106  * Returns true if a is greater than b.
01107  *
01108  * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce).
01109  */
01110 static VALUE
01111 BigDecimal_gt(VALUE self, VALUE r)
01112 {
01113     return BigDecimalCmp(self, r, '>');
01114 }
01115 
01116 /* call-seq:
01117  * a >= b
01118  *
01119  * Returns true if a is greater than or equal to b.
01120  *
01121  * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce)
01122  */
01123 static VALUE
01124 BigDecimal_ge(VALUE self, VALUE r)
01125 {
01126     return BigDecimalCmp(self, r, 'G');
01127 }
01128 
01129 /*
01130  * call-seq: -@
01131  *
01132  * Return the negation of self.
01133  *
01134  * e.g.
01135  *   b = -a
01136  *   b == a * -1
01137  */
01138 static VALUE
01139 BigDecimal_neg(VALUE self)
01140 {
01141     ENTER(5);
01142     Real *c, *a;
01143     GUARD_OBJ(a,GetVpValue(self,1));
01144     GUARD_OBJ(c,VpCreateRbObject(a->Prec *(VpBaseFig() + 1), "0"));
01145     VpAsgn(c, a, -1);
01146     return ToValue(c);
01147 }
01148 
01149  /*
01150   * Document-method: BigDecimal#mult
01151   *
01152   * call-seq: mult(value, digits)
01153   *
01154   * Multiply by the specified value.
01155   *
01156   * e.g.
01157   *   c = a.mult(b,n)
01158   *   c = a * b
01159   *
01160   * digits:: If specified and less than the number of significant digits of the
01161   * result, the result is rounded to that number of digits, according to
01162   * BigDecimal.mode.
01163   */
01164 static VALUE
01165 BigDecimal_mult(VALUE self, VALUE r)
01166 {
01167     ENTER(5);
01168     Real *c, *a, *b;
01169     size_t mx;
01170 
01171     GUARD_OBJ(a,GetVpValue(self,1));
01172     if (RB_TYPE_P(r, T_FLOAT)) {
01173         b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
01174     }
01175     else if (RB_TYPE_P(r, T_RATIONAL)) {
01176         b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
01177     }
01178     else {
01179         b = GetVpValue(r,0);
01180     }
01181 
01182     if(!b) return DoSomeOne(self,r,'*');
01183     SAVE(b);
01184 
01185     mx = a->Prec + b->Prec;
01186     GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0"));
01187     VpMult(c, a, b);
01188     return ToValue(c);
01189 }
01190 
01191 static VALUE
01192 BigDecimal_divide(Real **c, Real **res, Real **div, VALUE self, VALUE r)
01193 /* For c = self.div(r): with round operation */
01194 {
01195     ENTER(5);
01196     Real *a, *b;
01197     size_t mx;
01198 
01199     GUARD_OBJ(a,GetVpValue(self,1));
01200     if (RB_TYPE_P(r, T_FLOAT)) {
01201         b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
01202     }
01203     else if (RB_TYPE_P(r, T_RATIONAL)) {
01204         b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
01205     }
01206     else {
01207         b = GetVpValue(r,0);
01208     }
01209 
01210     if(!b) return DoSomeOne(self,r,'/');
01211     SAVE(b);
01212 
01213     *div = b;
01214     mx = a->Prec + vabs(a->exponent);
01215     if(mx<b->Prec + vabs(b->exponent)) mx = b->Prec + vabs(b->exponent);
01216     mx =(mx + 1) * VpBaseFig();
01217     GUARD_OBJ((*c),VpCreateRbObject(mx, "#0"));
01218     GUARD_OBJ((*res),VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
01219     VpDivd(*c, *res, a, b);
01220     return (VALUE)0;
01221 }
01222 
01223  /* call-seq:
01224   * div(value, digits)
01225   * quo(value)
01226   *
01227   * Divide by the specified value.
01228   *
01229   * e.g.
01230   *   c = a.div(b,n)
01231   *
01232   * digits:: If specified and less than the number of significant digits of the
01233   * result, the result is rounded to that number of digits, according to
01234   * BigDecimal.mode.
01235   *
01236   * If digits is 0, the result is the same as the / operator. If not, the
01237   * result is an integer BigDecimal, by analogy with Float#div.
01238   *
01239   * The alias quo is provided since <code>div(value, 0)</code> is the same as
01240   * computing the quotient; see BigDecimal#divmod.
01241   */
01242 static VALUE
01243 BigDecimal_div(VALUE self, VALUE r)
01244 /* For c = self/r: with round operation */
01245 {
01246     ENTER(5);
01247     Real *c=NULL, *res=NULL, *div = NULL;
01248     r = BigDecimal_divide(&c, &res, &div, self, r);
01249     if(r!=(VALUE)0) return r; /* coerced by other */
01250     SAVE(c);SAVE(res);SAVE(div);
01251     /* a/b = c + r/b */
01252     /* c xxxxx
01253        r 00000yyyyy  ==> (y/b)*BASE >= HALF_BASE
01254      */
01255     /* Round */
01256     if(VpHasVal(div)) { /* frac[0] must be zero for NaN,INF,Zero */
01257         VpInternalRound(c, 0, c->frac[c->Prec-1], (BDIGIT)(VpBaseVal()*(BDIGIT_DBL)res->frac[0]/div->frac[0]));
01258     }
01259     return ToValue(c);
01260 }
01261 
01262 /*
01263  * %: mod = a%b = a - (a.to_f/b).floor * b
01264  * div = (a.to_f/b).floor
01265  */
01266 static VALUE
01267 BigDecimal_DoDivmod(VALUE self, VALUE r, Real **div, Real **mod)
01268 {
01269     ENTER(8);
01270     Real *c=NULL, *d=NULL, *res=NULL;
01271     Real *a, *b;
01272     size_t mx;
01273 
01274     GUARD_OBJ(a,GetVpValue(self,1));
01275     if (RB_TYPE_P(r, T_FLOAT)) {
01276         b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
01277     }
01278     else if (RB_TYPE_P(r, T_RATIONAL)) {
01279         b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
01280     }
01281     else {
01282         b = GetVpValue(r,0);
01283     }
01284 
01285     if(!b) return Qfalse;
01286     SAVE(b);
01287 
01288     if(VpIsNaN(a) || VpIsNaN(b)) goto NaN;
01289     if(VpIsInf(a) && VpIsInf(b)) goto NaN;
01290     if(VpIsZero(b)) {
01291         rb_raise(rb_eZeroDivError, "divided by 0");
01292     }
01293     if(VpIsInf(a)) {
01294        GUARD_OBJ(d,VpCreateRbObject(1, "0"));
01295        VpSetInf(d, (SIGNED_VALUE)(VpGetSign(a) == VpGetSign(b) ? 1 : -1));
01296        GUARD_OBJ(c,VpCreateRbObject(1, "NaN"));
01297        *div = d;
01298        *mod = c;
01299        return Qtrue;
01300     }
01301     if(VpIsInf(b)) {
01302        GUARD_OBJ(d,VpCreateRbObject(1, "0"));
01303        *div = d;
01304        *mod = a;
01305        return Qtrue;
01306     }
01307     if(VpIsZero(a)) {
01308        GUARD_OBJ(c,VpCreateRbObject(1, "0"));
01309        GUARD_OBJ(d,VpCreateRbObject(1, "0"));
01310        *div = d;
01311        *mod = c;
01312        return Qtrue;
01313     }
01314 
01315     mx = a->Prec + vabs(a->exponent);
01316     if(mx<b->Prec + vabs(b->exponent)) mx = b->Prec + vabs(b->exponent);
01317     mx =(mx + 1) * VpBaseFig();
01318     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01319     GUARD_OBJ(res,VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
01320     VpDivd(c, res, a, b);
01321     mx = c->Prec *(VpBaseFig() + 1);
01322     GUARD_OBJ(d,VpCreateRbObject(mx, "0"));
01323     VpActiveRound(d,c,VP_ROUND_DOWN,0);
01324     VpMult(res,d,b);
01325     VpAddSub(c,a,res,-1);
01326     if(!VpIsZero(c) && (VpGetSign(a)*VpGetSign(b)<0)) {
01327         VpAddSub(res,d,VpOne(),-1);
01328         GUARD_OBJ(d,VpCreateRbObject(GetAddSubPrec(c, b)*(VpBaseFig() + 1), "0"));
01329         VpAddSub(d  ,c,b,       1);
01330         *div = res;
01331         *mod = d;
01332     } else {
01333         *div = d;
01334         *mod = c;
01335     }
01336     return Qtrue;
01337 
01338 NaN:
01339     GUARD_OBJ(c,VpCreateRbObject(1, "NaN"));
01340     GUARD_OBJ(d,VpCreateRbObject(1, "NaN"));
01341     *div = d;
01342     *mod = c;
01343     return Qtrue;
01344 }
01345 
01346 /* call-seq:
01347  * a % b
01348  * a.modulo(b)
01349  *
01350  * Returns the modulus from dividing by b.
01351  *
01352  * See BigDecimal#divmod.
01353  */
01354 static VALUE
01355 BigDecimal_mod(VALUE self, VALUE r) /* %: a%b = a - (a.to_f/b).floor * b */
01356 {
01357     ENTER(3);
01358     Real *div=NULL, *mod=NULL;
01359 
01360     if(BigDecimal_DoDivmod(self,r,&div,&mod)) {
01361         SAVE(div); SAVE(mod);
01362         return ToValue(mod);
01363     }
01364     return DoSomeOne(self,r,'%');
01365 }
01366 
01367 static VALUE
01368 BigDecimal_divremain(VALUE self, VALUE r, Real **dv, Real **rv)
01369 {
01370     ENTER(10);
01371     size_t mx;
01372     Real *a=NULL, *b=NULL, *c=NULL, *res=NULL, *d=NULL, *rr=NULL, *ff=NULL;
01373     Real *f=NULL;
01374 
01375     GUARD_OBJ(a,GetVpValue(self,1));
01376     if (RB_TYPE_P(r, T_FLOAT)) {
01377         b = GetVpValueWithPrec(r, DBL_DIG+1, 1);
01378     }
01379     else if (RB_TYPE_P(r, T_RATIONAL)) {
01380         b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
01381     }
01382     else {
01383         b = GetVpValue(r,0);
01384     }
01385 
01386     if(!b) return DoSomeOne(self,r,rb_intern("remainder"));
01387     SAVE(b);
01388 
01389     mx  =(a->MaxPrec + b->MaxPrec) *VpBaseFig();
01390     GUARD_OBJ(c  ,VpCreateRbObject(mx, "0"));
01391     GUARD_OBJ(res,VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
01392     GUARD_OBJ(rr ,VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
01393     GUARD_OBJ(ff ,VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0"));
01394 
01395     VpDivd(c, res, a, b);
01396 
01397     mx = c->Prec *(VpBaseFig() + 1);
01398 
01399     GUARD_OBJ(d,VpCreateRbObject(mx, "0"));
01400     GUARD_OBJ(f,VpCreateRbObject(mx, "0"));
01401 
01402     VpActiveRound(d,c,VP_ROUND_DOWN,0); /* 0: round off */
01403 
01404     VpFrac(f, c);
01405     VpMult(rr,f,b);
01406     VpAddSub(ff,res,rr,1);
01407 
01408     *dv = d;
01409     *rv = ff;
01410     return (VALUE)0;
01411 }
01412 
01413 /* Returns the remainder from dividing by the value.
01414  *
01415  * x.remainder(y) means x-y*(x/y).truncate
01416  */
01417 static VALUE
01418 BigDecimal_remainder(VALUE self, VALUE r) /* remainder */
01419 {
01420     VALUE  f;
01421     Real  *d,*rv=0;
01422     f = BigDecimal_divremain(self,r,&d,&rv);
01423     if(f!=(VALUE)0) return f;
01424     return ToValue(rv);
01425 }
01426 
01427 /* Divides by the specified value, and returns the quotient and modulus
01428  * as BigDecimal numbers. The quotient is rounded towards negative infinity.
01429  *
01430  * For example:
01431  *
01432  * require 'bigdecimal'
01433  *
01434  * a = BigDecimal.new("42")
01435  * b = BigDecimal.new("9")
01436  *
01437  * q,m = a.divmod(b)
01438  *
01439  * c = q * b + m
01440  *
01441  * a == c  -> true
01442  *
01443  * The quotient q is (a/b).floor, and the modulus is the amount that must be
01444  * added to q * b to get a.
01445  */
01446 static VALUE
01447 BigDecimal_divmod(VALUE self, VALUE r)
01448 {
01449     ENTER(5);
01450     Real *div=NULL, *mod=NULL;
01451 
01452     if(BigDecimal_DoDivmod(self,r,&div,&mod)) {
01453         SAVE(div); SAVE(mod);
01454         return rb_assoc_new(ToValue(div), ToValue(mod));
01455     }
01456     return DoSomeOne(self,r,rb_intern("divmod"));
01457 }
01458 
01459 /*
01460  * See BigDecimal#quo
01461  */
01462 static VALUE
01463 BigDecimal_div2(int argc, VALUE *argv, VALUE self)
01464 {
01465     ENTER(5);
01466     VALUE b,n;
01467     int na = rb_scan_args(argc,argv,"11",&b,&n);
01468     if(na==1) { /* div in Float sense */
01469        Real *div=NULL;
01470        Real *mod;
01471        if(BigDecimal_DoDivmod(self,b,&div,&mod)) {
01472           return BigDecimal_to_i(ToValue(div));
01473        }
01474        return DoSomeOne(self,b,rb_intern("div"));
01475     } else {    /* div in BigDecimal sense */
01476        SIGNED_VALUE ix = GetPositiveInt(n);
01477        if (ix == 0) return BigDecimal_div(self, b);
01478        else {
01479           Real *res=NULL;
01480           Real *av=NULL, *bv=NULL, *cv=NULL;
01481           size_t mx = (ix+VpBaseFig()*2);
01482           size_t pl = VpSetPrecLimit(0);
01483 
01484           GUARD_OBJ(cv,VpCreateRbObject(mx,"0"));
01485           GUARD_OBJ(av,GetVpValue(self,1));
01486           GUARD_OBJ(bv,GetVpValue(b,1));
01487           mx = av->Prec + bv->Prec + 2;
01488           if(mx <= cv->MaxPrec) mx = cv->MaxPrec+1;
01489           GUARD_OBJ(res,VpCreateRbObject((mx * 2  + 2)*VpBaseFig(), "#0"));
01490           VpDivd(cv,res,av,bv);
01491           VpSetPrecLimit(pl);
01492           VpLeftRound(cv,VpGetRoundMode(),ix);
01493           return ToValue(cv);
01494        }
01495     }
01496 }
01497 
01498 static VALUE
01499 BigDecimal_add2(VALUE self, VALUE b, VALUE n)
01500 {
01501     ENTER(2);
01502     Real   *cv;
01503     SIGNED_VALUE mx = GetPositiveInt(n);
01504     if (mx == 0) return BigDecimal_add(self, b);
01505     else {
01506        size_t pl = VpSetPrecLimit(0);
01507        VALUE   c = BigDecimal_add(self,b);
01508        VpSetPrecLimit(pl);
01509        GUARD_OBJ(cv,GetVpValue(c,1));
01510        VpLeftRound(cv,VpGetRoundMode(),mx);
01511        return ToValue(cv);
01512     }
01513 }
01514 
01515 static VALUE
01516 BigDecimal_sub2(VALUE self, VALUE b, VALUE n)
01517 {
01518     ENTER(2);
01519     Real *cv;
01520     SIGNED_VALUE mx = GetPositiveInt(n);
01521     if (mx == 0) return BigDecimal_sub(self, b);
01522     else {
01523        size_t pl = VpSetPrecLimit(0);
01524        VALUE   c = BigDecimal_sub(self,b);
01525        VpSetPrecLimit(pl);
01526        GUARD_OBJ(cv,GetVpValue(c,1));
01527        VpLeftRound(cv,VpGetRoundMode(),mx);
01528        return ToValue(cv);
01529     }
01530 }
01531 
01532 static VALUE
01533 BigDecimal_mult2(VALUE self, VALUE b, VALUE n)
01534 {
01535     ENTER(2);
01536     Real *cv;
01537     SIGNED_VALUE mx = GetPositiveInt(n);
01538     if (mx == 0) return BigDecimal_mult(self, b);
01539     else {
01540        size_t pl = VpSetPrecLimit(0);
01541        VALUE   c = BigDecimal_mult(self,b);
01542        VpSetPrecLimit(pl);
01543        GUARD_OBJ(cv,GetVpValue(c,1));
01544        VpLeftRound(cv,VpGetRoundMode(),mx);
01545        return ToValue(cv);
01546     }
01547 }
01548 
01549 /* Returns the absolute value.
01550  *
01551  * BigDecimal('5').abs -> 5
01552  *
01553  * BigDecimal('-3').abs -> 3
01554  */
01555 static VALUE
01556 BigDecimal_abs(VALUE self)
01557 {
01558     ENTER(5);
01559     Real *c, *a;
01560     size_t mx;
01561 
01562     GUARD_OBJ(a,GetVpValue(self,1));
01563     mx = a->Prec *(VpBaseFig() + 1);
01564     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01565     VpAsgn(c, a, 1);
01566     VpChangeSign(c, 1);
01567     return ToValue(c);
01568 }
01569 
01570 /* call-seq:
01571  * sqrt(n)
01572  *
01573  * Returns the square root of the value.
01574  *
01575  * Result has at least n significant digits.
01576  */
01577 static VALUE
01578 BigDecimal_sqrt(VALUE self, VALUE nFig)
01579 {
01580     ENTER(5);
01581     Real *c, *a;
01582     size_t mx, n;
01583 
01584     GUARD_OBJ(a,GetVpValue(self,1));
01585     mx = a->Prec *(VpBaseFig() + 1);
01586 
01587     n = GetPositiveInt(nFig) + VpDblFig() + 1;
01588     if(mx <= n) mx = n;
01589     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01590     VpSqrt(c, a);
01591     return ToValue(c);
01592 }
01593 
01594 /* Return the integer part of the number.
01595  */
01596 static VALUE
01597 BigDecimal_fix(VALUE self)
01598 {
01599     ENTER(5);
01600     Real *c, *a;
01601     size_t mx;
01602 
01603     GUARD_OBJ(a,GetVpValue(self,1));
01604     mx = a->Prec *(VpBaseFig() + 1);
01605     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01606     VpActiveRound(c,a,VP_ROUND_DOWN,0); /* 0: round off */
01607     return ToValue(c);
01608 }
01609 
01610 /* call-seq:
01611  * round(n, mode)
01612  *
01613  * Round to the nearest 1 (by default), returning the result as a BigDecimal.
01614  *
01615  *      BigDecimal('3.14159').round #=> 3
01616  *      BigDecimal('8.7').round #=> 9
01617  *
01618  * If n is specified and positive, the fractional part of the result has no
01619  * more than that many digits.
01620  *
01621  * If n is specified and negative, at least that many digits to the left of the
01622  * decimal point will be 0 in the result.
01623  *
01624  *      BigDecimal('3.14159').round(3) #=> 3.142
01625  *      BigDecimal('13345.234').round(-2) #=> 13300.0
01626  *
01627  * The value of the optional mode argument can be used to determine how
01628  * rounding is performed; see BigDecimal.mode.
01629  */
01630 static VALUE
01631 BigDecimal_round(int argc, VALUE *argv, VALUE self)
01632 {
01633     ENTER(5);
01634     Real   *c, *a;
01635     int    iLoc = 0;
01636     VALUE  vLoc;
01637     VALUE  vRound;
01638     size_t mx, pl;
01639 
01640     unsigned short sw = VpGetRoundMode();
01641 
01642     switch (rb_scan_args(argc, argv, "02", &vLoc, &vRound)) {
01643     case 0:
01644         iLoc = 0;
01645         break;
01646     case 1:
01647         Check_Type(vLoc, T_FIXNUM);
01648         iLoc = FIX2INT(vLoc);
01649         break;
01650     case 2:
01651         Check_Type(vLoc, T_FIXNUM);
01652         iLoc = FIX2INT(vLoc);
01653         sw = check_rounding_mode(vRound);
01654         break;
01655     }
01656 
01657     pl = VpSetPrecLimit(0);
01658     GUARD_OBJ(a,GetVpValue(self,1));
01659     mx = a->Prec *(VpBaseFig() + 1);
01660     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01661     VpSetPrecLimit(pl);
01662     VpActiveRound(c,a,sw,iLoc);
01663     if (argc == 0) {
01664         return BigDecimal_to_i(ToValue(c));
01665     }
01666     return ToValue(c);
01667 }
01668 
01669 /* call-seq:
01670  * truncate(n)
01671  *
01672  * Truncate to the nearest 1, returning the result as a BigDecimal.
01673  *
01674  *      BigDecimal('3.14159').truncate #=> 3
01675  *      BigDecimal('8.7').truncate #=> 8
01676  *
01677  * If n is specified and positive, the fractional part of the result has no
01678  * more than that many digits.
01679  *
01680  * If n is specified and negative, at least that many digits to the left of the
01681  * decimal point will be 0 in the result.
01682  *
01683  *      BigDecimal('3.14159').truncate(3) #=> 3.141
01684  *      BigDecimal('13345.234').truncate(-2) #=> 13300.0
01685  */
01686 static VALUE
01687 BigDecimal_truncate(int argc, VALUE *argv, VALUE self)
01688 {
01689     ENTER(5);
01690     Real *c, *a;
01691     int iLoc;
01692     VALUE vLoc;
01693     size_t mx, pl = VpSetPrecLimit(0);
01694 
01695     if(rb_scan_args(argc,argv,"01",&vLoc)==0) {
01696         iLoc = 0;
01697     } else {
01698         Check_Type(vLoc, T_FIXNUM);
01699         iLoc = FIX2INT(vLoc);
01700     }
01701 
01702     GUARD_OBJ(a,GetVpValue(self,1));
01703     mx = a->Prec *(VpBaseFig() + 1);
01704     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01705     VpSetPrecLimit(pl);
01706     VpActiveRound(c,a,VP_ROUND_DOWN,iLoc); /* 0: truncate */
01707     if (argc == 0) {
01708         return BigDecimal_to_i(ToValue(c));
01709     }
01710     return ToValue(c);
01711 }
01712 
01713 /* Return the fractional part of the number.
01714  */
01715 static VALUE
01716 BigDecimal_frac(VALUE self)
01717 {
01718     ENTER(5);
01719     Real *c, *a;
01720     size_t mx;
01721 
01722     GUARD_OBJ(a,GetVpValue(self,1));
01723     mx = a->Prec *(VpBaseFig() + 1);
01724     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01725     VpFrac(c, a);
01726     return ToValue(c);
01727 }
01728 
01729 /* call-seq:
01730  * floor(n)
01731  *
01732  * Return the largest integer less than or equal to the value, as a BigDecimal.
01733  *
01734  *      BigDecimal('3.14159').floor #=> 3
01735  *      BigDecimal('-9.1').floor #=> -10
01736  *
01737  * If n is specified and positive, the fractional part of the result has no
01738  * more than that many digits.
01739  *
01740  * If n is specified and negative, at least that
01741  * many digits to the left of the decimal point will be 0 in the result.
01742  *
01743  *      BigDecimal('3.14159').floor(3) #=> 3.141
01744  *      BigDecimal('13345.234').floor(-2) #=> 13300.0
01745  */
01746 static VALUE
01747 BigDecimal_floor(int argc, VALUE *argv, VALUE self)
01748 {
01749     ENTER(5);
01750     Real *c, *a;
01751     int iLoc;
01752     VALUE vLoc;
01753     size_t mx, pl = VpSetPrecLimit(0);
01754 
01755     if(rb_scan_args(argc,argv,"01",&vLoc)==0) {
01756         iLoc = 0;
01757     } else {
01758         Check_Type(vLoc, T_FIXNUM);
01759         iLoc = FIX2INT(vLoc);
01760     }
01761 
01762     GUARD_OBJ(a,GetVpValue(self,1));
01763     mx = a->Prec *(VpBaseFig() + 1);
01764     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01765     VpSetPrecLimit(pl);
01766     VpActiveRound(c,a,VP_ROUND_FLOOR,iLoc);
01767 #ifdef BIGDECIMAL_DEBUG
01768     VPrint(stderr, "floor: c=%\n", c);
01769 #endif
01770     if (argc == 0) {
01771         return BigDecimal_to_i(ToValue(c));
01772     }
01773     return ToValue(c);
01774 }
01775 
01776 /* call-seq:
01777  * ceil(n)
01778  *
01779  * Return the smallest integer greater than or equal to the value, as a BigDecimal.
01780  *
01781  *      BigDecimal('3.14159').ceil #=> 4
01782  *      BigDecimal('-9.1').ceil #=> -9
01783  *
01784  * If n is specified and positive, the fractional part of the result has no
01785  * more than that many digits.
01786  *
01787  * If n is specified and negative, at least that
01788  * many digits to the left of the decimal point will be 0 in the result.
01789  *
01790  *      BigDecimal('3.14159').ceil(3) #=> 3.142
01791  *      BigDecimal('13345.234').ceil(-2) #=> 13400.0
01792  */
01793 static VALUE
01794 BigDecimal_ceil(int argc, VALUE *argv, VALUE self)
01795 {
01796     ENTER(5);
01797     Real *c, *a;
01798     int iLoc;
01799     VALUE vLoc;
01800     size_t mx, pl = VpSetPrecLimit(0);
01801 
01802     if(rb_scan_args(argc,argv,"01",&vLoc)==0) {
01803         iLoc = 0;
01804     } else {
01805         Check_Type(vLoc, T_FIXNUM);
01806         iLoc = FIX2INT(vLoc);
01807     }
01808 
01809     GUARD_OBJ(a,GetVpValue(self,1));
01810     mx = a->Prec *(VpBaseFig() + 1);
01811     GUARD_OBJ(c,VpCreateRbObject(mx, "0"));
01812     VpSetPrecLimit(pl);
01813     VpActiveRound(c,a,VP_ROUND_CEIL,iLoc);
01814     if (argc == 0) {
01815         return BigDecimal_to_i(ToValue(c));
01816     }
01817     return ToValue(c);
01818 }
01819 
01820 /* call-seq:
01821  * to_s(s)
01822  *
01823  * Converts the value to a string.
01824  *
01825  * The default format looks like  0.xxxxEnn.
01826  *
01827  * The optional parameter s consists of either an integer; or an optional '+'
01828  * or ' ', followed by an optional number, followed by an optional 'E' or 'F'.
01829  *
01830  * If there is a '+' at the start of s, positive values are returned with
01831  * a leading '+'.
01832  *
01833  * A space at the start of s returns positive values with a leading space.
01834  *
01835  * If s contains a number, a space is inserted after each group of that many
01836  * fractional digits.
01837  *
01838  * If s ends with an 'E', engineering notation (0.xxxxEnn) is used.
01839  *
01840  * If s ends with an 'F', conventional floating point notation is used.
01841  *
01842  * Examples:
01843  *
01844  *      BigDecimal.new('-123.45678901234567890').to_s('5F')
01845  *          #=> '-123.45678 90123 45678 9'
01846  *
01847  *      BigDecimal.new('123.45678901234567890').to_s('+8F')
01848  *          #=> '+123.45678901 23456789'
01849  *
01850  *      BigDecimal.new('123.45678901234567890').to_s(' F')
01851  *          #=> ' 123.4567890123456789'
01852  */
01853 static VALUE
01854 BigDecimal_to_s(int argc, VALUE *argv, VALUE self)
01855 {
01856     ENTER(5);
01857     int   fmt = 0;   /* 0:E format */
01858     int   fPlus = 0; /* =0:default,=1: set ' ' before digits ,set '+' before digits. */
01859     Real  *vp;
01860     volatile VALUE str;
01861     char  *psz;
01862     char   ch;
01863     size_t nc, mc = 0;
01864     VALUE  f;
01865 
01866     GUARD_OBJ(vp,GetVpValue(self,1));
01867 
01868     if (rb_scan_args(argc,argv,"01",&f)==1) {
01869         if (RB_TYPE_P(f, T_STRING)) {
01870             SafeStringValue(f);
01871             psz = RSTRING_PTR(f);
01872             if (*psz == ' ') {
01873                 fPlus = 1;
01874                 psz++;
01875             }
01876             else if (*psz == '+') {
01877                 fPlus = 2;
01878                 psz++;
01879             }
01880             while ((ch = *psz++) != 0) {
01881                 if (ISSPACE(ch)) {
01882                     continue;
01883                 }
01884                 if (!ISDIGIT(ch)) {
01885                     if (ch == 'F' || ch == 'f') {
01886                         fmt = 1; /* F format */
01887                     }
01888                     break;
01889                 }
01890                 mc = mc * 10 + ch - '0';
01891             }
01892         }
01893         else {
01894             mc = (size_t)GetPositiveInt(f);
01895         }
01896     }
01897     if (fmt) {
01898         nc = VpNumOfChars(vp, "F");
01899     }
01900     else {
01901         nc = VpNumOfChars(vp, "E");
01902     }
01903     if (mc > 0) {
01904         nc += (nc + mc - 1) / mc + 1;
01905     }
01906 
01907     str = rb_str_new(0, nc);
01908     psz = RSTRING_PTR(str);
01909 
01910     if (fmt) {
01911         VpToFString(vp, psz, mc, fPlus);
01912     }
01913     else {
01914         VpToString (vp, psz, mc, fPlus);
01915     }
01916     rb_str_resize(str, strlen(psz));
01917     return str;
01918 }
01919 
01920 /* Splits a BigDecimal number into four parts, returned as an array of values.
01921  *
01922  * The first value represents the sign of the BigDecimal, and is -1 or 1, or 0
01923  * if the BigDecimal is Not a Number.
01924  *
01925  * The second value is a string representing the significant digits of the
01926  * BigDecimal, with no leading zeros.
01927  *
01928  * The third value is the base used for arithmetic (currently always 10) as an
01929  * Integer.
01930  *
01931  * The fourth value is an Integer exponent.
01932  *
01933  * If the BigDecimal can be represented as 0.xxxxxx*10**n, then xxxxxx is the
01934  * string of significant digits with no leading zeros, and n is the exponent.
01935  *
01936  * From these values, you can translate a BigDecimal to a float as follows:
01937  *
01938  *   sign, significant_digits, base, exponent = a.split
01939  *   f = sign * "0.#{significant_digits}".to_f * (base ** exponent)
01940  *
01941  * (Note that the to_f method is provided as a more convenient way to translate
01942  * a BigDecimal to a Float.)
01943  */
01944 static VALUE
01945 BigDecimal_split(VALUE self)
01946 {
01947     ENTER(5);
01948     Real *vp;
01949     VALUE obj,str;
01950     ssize_t e, s;
01951     char *psz1;
01952 
01953     GUARD_OBJ(vp,GetVpValue(self,1));
01954     str = rb_str_new(0, VpNumOfChars(vp,"E"));
01955     psz1 = RSTRING_PTR(str);
01956     VpSzMantissa(vp,psz1);
01957     s = 1;
01958     if(psz1[0]=='-') {
01959         size_t len = strlen(psz1+1);
01960 
01961         memmove(psz1, psz1+1, len);
01962         psz1[len] = '\0';
01963         s = -1;
01964     }
01965     if(psz1[0]=='N') s=0; /* NaN */
01966     e = VpExponent10(vp);
01967     obj  = rb_ary_new2(4);
01968     rb_ary_push(obj, INT2FIX(s));
01969     rb_ary_push(obj, str);
01970     rb_str_resize(str, strlen(psz1));
01971     rb_ary_push(obj, INT2FIX(10));
01972     rb_ary_push(obj, INT2NUM(e));
01973     return obj;
01974 }
01975 
01976 /* Returns the exponent of the BigDecimal number, as an Integer.
01977  *
01978  * If the number can be represented as 0.xxxxxx*10**n where xxxxxx is a string
01979  * of digits with no leading zeros, then n is the exponent.
01980  */
01981 static VALUE
01982 BigDecimal_exponent(VALUE self)
01983 {
01984     ssize_t e = VpExponent10(GetVpValue(self, 1));
01985     return INT2NUM(e);
01986 }
01987 
01988 /* Returns debugging information about the value as a string of comma-separated
01989  * values in angle brackets with a leading #:
01990  *
01991  * BigDecimal.new("1234.5678").inspect ->
01992  * "#<BigDecimal:b7ea1130,'0.12345678E4',8(12)>"
01993  *
01994  * The first part is the address, the second is the value as a string, and
01995  * the final part ss(mm) is the current number of significant digits and the
01996  * maximum number of significant digits, respectively.
01997  */
01998 static VALUE
01999 BigDecimal_inspect(VALUE self)
02000 {
02001     ENTER(5);
02002     Real *vp;
02003     volatile VALUE obj;
02004     size_t nc;
02005     char *psz, *tmp;
02006 
02007     GUARD_OBJ(vp,GetVpValue(self,1));
02008     nc = VpNumOfChars(vp,"E");
02009     nc +=(nc + 9) / 10;
02010 
02011     obj = rb_str_new(0, nc+256);
02012     psz = RSTRING_PTR(obj);
02013     sprintf(psz,"#<BigDecimal:%"PRIxVALUE",'",self);
02014     tmp = psz + strlen(psz);
02015     VpToString(vp, tmp, 10, 0);
02016     tmp += strlen(tmp);
02017     sprintf(tmp, "',%"PRIuSIZE"(%"PRIuSIZE")>", VpPrec(vp)*VpBaseFig(), VpMaxPrec(vp)*VpBaseFig());
02018     rb_str_resize(obj, strlen(psz));
02019     return obj;
02020 }
02021 
02022 static VALUE BigMath_s_exp(VALUE, VALUE, VALUE);
02023 static VALUE BigMath_s_log(VALUE, VALUE, VALUE);
02024 
02025 #define BigMath_exp(x, n) BigMath_s_exp(rb_mBigMath, (x), (n))
02026 #define BigMath_log(x, n) BigMath_s_log(rb_mBigMath, (x), (n))
02027 
02028 inline static int
02029 is_integer(VALUE x)
02030 {
02031     return (RB_TYPE_P(x, T_FIXNUM) || RB_TYPE_P(x, T_BIGNUM));
02032 }
02033 
02034 inline static int
02035 is_negative(VALUE x)
02036 {
02037     if (FIXNUM_P(x)) {
02038         return FIX2LONG(x) < 0;
02039     }
02040     else if (RB_TYPE_P(x, T_BIGNUM)) {
02041         return RBIGNUM_NEGATIVE_P(x);
02042     }
02043     else if (RB_TYPE_P(x, T_FLOAT)) {
02044         return RFLOAT_VALUE(x) < 0.0;
02045     }
02046     return RTEST(rb_funcall(x, '<', 1, INT2FIX(0)));
02047 }
02048 
02049 #define is_positive(x) (!is_negative(x))
02050 
02051 inline static int
02052 is_zero(VALUE x)
02053 {
02054     VALUE num;
02055 
02056     switch (TYPE(x)) {
02057       case T_FIXNUM:
02058         return FIX2LONG(x) == 0;
02059 
02060       case T_BIGNUM:
02061         return Qfalse;
02062 
02063       case T_RATIONAL:
02064         num = RRATIONAL(x)->num;
02065         return FIXNUM_P(num) && FIX2LONG(num) == 0;
02066 
02067       default:
02068         break;
02069     }
02070 
02071     return RTEST(rb_funcall(x, id_eq, 1, INT2FIX(0)));
02072 }
02073 
02074 inline static int
02075 is_one(VALUE x)
02076 {
02077     VALUE num, den;
02078 
02079     switch (TYPE(x)) {
02080       case T_FIXNUM:
02081         return FIX2LONG(x) == 1;
02082 
02083       case T_BIGNUM:
02084         return Qfalse;
02085 
02086       case T_RATIONAL:
02087         num = RRATIONAL(x)->num;
02088         den = RRATIONAL(x)->den;
02089         return FIXNUM_P(den) && FIX2LONG(den) == 1 &&
02090                FIXNUM_P(num) && FIX2LONG(num) == 1;
02091 
02092       default:
02093         break;
02094     }
02095 
02096     return RTEST(rb_funcall(x, id_eq, 1, INT2FIX(1)));
02097 }
02098 
02099 inline static int
02100 is_even(VALUE x)
02101 {
02102     switch (TYPE(x)) {
02103       case T_FIXNUM:
02104         return (FIX2LONG(x) % 2) == 0;
02105 
02106       case T_BIGNUM:
02107         return (RBIGNUM_DIGITS(x)[0] % 2) == 0;
02108 
02109       default:
02110         break;
02111     }
02112 
02113     return 0;
02114 }
02115 
02116 static VALUE
02117 rmpd_power_by_big_decimal(Real const* x, Real const* exp, ssize_t const n)
02118 {
02119     VALUE log_x, multiplied, y;
02120     volatile VALUE obj = exp->obj;
02121 
02122     if (VpIsZero(exp)) {
02123         return ToValue(VpCreateRbObject(n, "1"));
02124     }
02125 
02126     log_x = BigMath_log(x->obj, SSIZET2NUM(n+1));
02127     multiplied = BigDecimal_mult2(exp->obj, log_x, SSIZET2NUM(n+1));
02128     y = BigMath_exp(multiplied, SSIZET2NUM(n));
02129     RB_GC_GUARD(obj);
02130 
02131     return y;
02132 }
02133 
02134 /* call-seq:
02135  * power(n)
02136  * power(n, prec)
02137  *
02138  * Returns the value raised to the power of n.
02139  *
02140  * Note that n must be an Integer.
02141  *
02142  * Also available as the operator **
02143  */
02144 static VALUE
02145 BigDecimal_power(int argc, VALUE*argv, VALUE self)
02146 {
02147     ENTER(5);
02148     VALUE vexp, prec;
02149     Real* exp = NULL;
02150     Real *x, *y;
02151     ssize_t mp, ma, n;
02152     SIGNED_VALUE int_exp;
02153     double d;
02154 
02155     rb_scan_args(argc, argv, "11", &vexp, &prec);
02156 
02157     GUARD_OBJ(x, GetVpValue(self, 1));
02158     n = NIL_P(prec) ? (ssize_t)(x->Prec*VpBaseFig()) : NUM2SSIZET(prec);
02159 
02160     if (VpIsNaN(x)) {
02161         y = VpCreateRbObject(n, "0#");
02162         RB_GC_GUARD(y->obj);
02163         VpSetNaN(y);
02164         return ToValue(y);
02165     }
02166 
02167 retry:
02168     switch (TYPE(vexp)) {
02169       case T_FIXNUM:
02170         break;
02171 
02172       case T_BIGNUM:
02173         break;
02174 
02175       case T_FLOAT:
02176         d = RFLOAT_VALUE(vexp);
02177         if (d == round(d)) {
02178             vexp = LL2NUM((LONG_LONG)round(d));
02179             goto retry;
02180         }
02181         exp = GetVpValueWithPrec(vexp, DBL_DIG+1, 1);
02182         break;
02183 
02184       case T_RATIONAL:
02185         if (is_zero(RRATIONAL(vexp)->num)) {
02186             if (is_positive(vexp)) {
02187                 vexp = INT2FIX(0);
02188                 goto retry;
02189             }
02190         }
02191         else if (is_one(RRATIONAL(vexp)->den)) {
02192             vexp = RRATIONAL(vexp)->num;
02193             goto retry;
02194         }
02195         exp = GetVpValueWithPrec(vexp, n, 1);
02196         break;
02197 
02198       case T_DATA:
02199         if (is_kind_of_BigDecimal(vexp)) {
02200             VALUE zero = INT2FIX(0);
02201             VALUE rounded = BigDecimal_round(1, &zero, vexp);
02202             if (RTEST(BigDecimal_eq(vexp, rounded))) {
02203                 vexp = BigDecimal_to_i(vexp);
02204                 goto retry;
02205             }
02206             exp = DATA_PTR(vexp);
02207             break;
02208         }
02209         /* fall through */
02210       default:
02211         rb_raise(rb_eTypeError,
02212                  "wrong argument type %"PRIsVALUE" (expected scalar Numeric)",
02213                  RB_OBJ_CLASSNAME(vexp));
02214     }
02215 
02216     if (VpIsZero(x)) {
02217         if (is_negative(vexp)) {
02218             y = VpCreateRbObject(n, "#0");
02219             RB_GC_GUARD(y->obj);
02220             if (VpGetSign(x) < 0) {
02221                 if (is_integer(vexp)) {
02222                     if (is_even(vexp)) {
02223                         /* (-0) ** (-even_integer)  -> Infinity */
02224                         VpSetPosInf(y);
02225                     }
02226                     else {
02227                         /* (-0) ** (-odd_integer)  -> -Infinity */
02228                         VpSetNegInf(y);
02229                     }
02230                 }
02231                 else {
02232                     /* (-0) ** (-non_integer)  -> Infinity */
02233                     VpSetPosInf(y);
02234                 }
02235             }
02236             else {
02237                 /* (+0) ** (-num)  -> Infinity */
02238                 VpSetPosInf(y);
02239             }
02240             return ToValue(y);
02241         }
02242         else if (is_zero(vexp)) {
02243             return ToValue(VpCreateRbObject(n, "1"));
02244         }
02245         else {
02246             return ToValue(VpCreateRbObject(n, "0"));
02247         }
02248     }
02249 
02250     if (is_zero(vexp)) {
02251         return ToValue(VpCreateRbObject(n, "1"));
02252     }
02253     else if (is_one(vexp)) {
02254         return self;
02255     }
02256 
02257     if (VpIsInf(x)) {
02258         if (is_negative(vexp)) {
02259             if (VpGetSign(x) < 0) {
02260                 if (is_integer(vexp)) {
02261                     if (is_even(vexp)) {
02262                         /* (-Infinity) ** (-even_integer) -> +0 */
02263                         return ToValue(VpCreateRbObject(n, "0"));
02264                     }
02265                     else {
02266                         /* (-Infinity) ** (-odd_integer) -> -0 */
02267                         return ToValue(VpCreateRbObject(n, "-0"));
02268                     }
02269                 }
02270                 else {
02271                     /* (-Infinity) ** (-non_integer) -> -0 */
02272                     return ToValue(VpCreateRbObject(n, "-0"));
02273                 }
02274             }
02275             else {
02276                 return ToValue(VpCreateRbObject(n, "0"));
02277             }
02278         }
02279         else {
02280             y = VpCreateRbObject(n, "0#");
02281             if (VpGetSign(x) < 0) {
02282                 if (is_integer(vexp)) {
02283                     if (is_even(vexp)) {
02284                         VpSetPosInf(y);
02285                     }
02286                     else {
02287                         VpSetNegInf(y);
02288                     }
02289                 }
02290                 else {
02291                     /* TODO: support complex */
02292                     rb_raise(rb_eMathDomainError,
02293                              "a non-integral exponent for a negative base");
02294                 }
02295             }
02296             else {
02297                 VpSetPosInf(y);
02298             }
02299             return ToValue(y);
02300         }
02301     }
02302 
02303     if (exp != NULL) {
02304         return rmpd_power_by_big_decimal(x, exp, n);
02305     }
02306     else if (RB_TYPE_P(vexp, T_BIGNUM)) {
02307         VALUE abs_value = BigDecimal_abs(self);
02308         if (is_one(abs_value)) {
02309             return ToValue(VpCreateRbObject(n, "1"));
02310         }
02311         else if (RTEST(rb_funcall(abs_value, '<', 1, INT2FIX(1)))) {
02312             if (is_negative(vexp)) {
02313                 y = VpCreateRbObject(n, "0#");
02314                 if (is_even(vexp)) {
02315                     VpSetInf(y, VpGetSign(x));
02316                 }
02317                 else {
02318                     VpSetInf(y, -VpGetSign(x));
02319                 }
02320                 return ToValue(y);
02321             }
02322             else if (VpGetSign(x) < 0 && is_even(vexp)) {
02323                 return ToValue(VpCreateRbObject(n, "-0"));
02324             }
02325             else {
02326                 return ToValue(VpCreateRbObject(n, "0"));
02327             }
02328         }
02329         else {
02330             if (is_positive(vexp)) {
02331                 y = VpCreateRbObject(n, "0#");
02332                 if (is_even(vexp)) {
02333                     VpSetInf(y, VpGetSign(x));
02334                 }
02335                 else {
02336                     VpSetInf(y, -VpGetSign(x));
02337                 }
02338                 return ToValue(y);
02339             }
02340             else if (VpGetSign(x) < 0 && is_even(vexp)) {
02341                 return ToValue(VpCreateRbObject(n, "-0"));
02342             }
02343             else {
02344                 return ToValue(VpCreateRbObject(n, "0"));
02345             }
02346         }
02347     }
02348 
02349     int_exp = FIX2INT(vexp);
02350     ma = int_exp;
02351     if (ma < 0)  ma = -ma;
02352     if (ma == 0) ma = 1;
02353 
02354     if (VpIsDef(x)) {
02355         mp = x->Prec * (VpBaseFig() + 1);
02356         GUARD_OBJ(y, VpCreateRbObject(mp * (ma + 1), "0"));
02357     }
02358     else {
02359         GUARD_OBJ(y, VpCreateRbObject(1, "0"));
02360     }
02361     VpPower(y, x, int_exp);
02362     return ToValue(y);
02363 }
02364 
02365 /* call-seq:
02366  *   big_decimal ** exp  -> big_decimal
02367  *
02368  * It is a synonym of BigDecimal#power(exp).
02369  */
02370 static VALUE
02371 BigDecimal_power_op(VALUE self, VALUE exp)
02372 {
02373     return BigDecimal_power(1, &exp, self);
02374 }
02375 
02376 static VALUE
02377 BigDecimal_s_allocate(VALUE klass)
02378 {
02379     return VpNewRbClass(0, NULL, klass)->obj;
02380 }
02381 
02382 static Real *BigDecimal_new(int argc, VALUE *argv);
02383 
02384 /* call-seq:
02385  *   new(initial, digits)
02386  *
02387  * Create a new BigDecimal object.
02388  *
02389  * initial:: The initial value, as an Integer, a Float, a Rational,
02390  *           a BigDecimal, or a String.
02391  *
02392  *           If it is a String, spaces are ignored and unrecognized characters
02393  *           terminate the value.
02394  *
02395  * digits:: The number of significant digits, as a Fixnum. If omitted or 0,
02396  *          the number of significant digits is determined from the initial
02397  *          value.
02398  *
02399  * The actual number of significant digits used in computation is usually
02400  * larger than the specified number.
02401  */
02402 static VALUE
02403 BigDecimal_initialize(int argc, VALUE *argv, VALUE self)
02404 {
02405     Real *pv = rb_check_typeddata(self, &BigDecimal_data_type);
02406     Real *x = BigDecimal_new(argc, argv);
02407 
02408     if (ToValue(x)) {
02409         pv = VpCopy(pv, x);
02410     }
02411     else {
02412         VpFree(pv);
02413         pv = x;
02414     }
02415     DATA_PTR(self) = pv;
02416     pv->obj = self;
02417     return self;
02418 }
02419 
02420 /* :nodoc:
02421  *
02422  * private method to dup and clone the provided BigDecimal +other+
02423  */
02424 static VALUE
02425 BigDecimal_initialize_copy(VALUE self, VALUE other)
02426 {
02427     Real *pv = rb_check_typeddata(self, &BigDecimal_data_type);
02428     Real *x = rb_check_typeddata(other, &BigDecimal_data_type);
02429 
02430     if (self != other) {
02431         DATA_PTR(self) = VpCopy(pv, x);
02432     }
02433     return self;
02434 }
02435 
02436 static Real *
02437 BigDecimal_new(int argc, VALUE *argv)
02438 {
02439     size_t mf;
02440     VALUE  nFig;
02441     VALUE  iniValue;
02442 
02443     if (rb_scan_args(argc, argv, "11", &iniValue, &nFig) == 1) {
02444         mf = 0;
02445     }
02446     else {
02447         mf = GetPositiveInt(nFig);
02448     }
02449 
02450     switch (TYPE(iniValue)) {
02451       case T_DATA:
02452         if (is_kind_of_BigDecimal(iniValue)) {
02453             return DATA_PTR(iniValue);
02454         }
02455         break;
02456 
02457       case T_FIXNUM:
02458         /* fall through */
02459       case T_BIGNUM:
02460         return GetVpValue(iniValue, 1);
02461 
02462       case T_FLOAT:
02463         if (mf > DBL_DIG+1) {
02464             rb_raise(rb_eArgError, "precision too large.");
02465         }
02466         /* fall through */
02467       case T_RATIONAL:
02468         if (NIL_P(nFig)) {
02469             rb_raise(rb_eArgError,
02470                      "can't omit precision for a %"PRIsVALUE".",
02471                      RB_OBJ_CLASSNAME(iniValue));
02472         }
02473         return GetVpValueWithPrec(iniValue, mf, 1);
02474 
02475       case T_STRING:
02476         /* fall through */
02477       default:
02478         break;
02479     }
02480     StringValueCStr(iniValue);
02481     return VpAlloc(mf, RSTRING_PTR(iniValue));
02482 }
02483 
02484 static VALUE
02485 BigDecimal_global_new(int argc, VALUE *argv, VALUE self)
02486 {
02487     Real *pv = BigDecimal_new(argc, argv);
02488     if (ToValue(pv)) pv = VpCopy(NULL, pv);
02489     pv->obj = TypedData_Wrap_Struct(rb_cBigDecimal, &BigDecimal_data_type, pv);
02490     return pv->obj;
02491 }
02492 
02493  /* call-seq:
02494   * BigDecimal.limit(digits)
02495   *
02496   * Limit the number of significant digits in newly created BigDecimal
02497   * numbers to the specified value. Rounding is performed as necessary,
02498   * as specified by BigDecimal.mode.
02499   *
02500   * A limit of 0, the default, means no upper limit.
02501   *
02502   * The limit specified by this method takes less priority over any limit
02503   * specified to instance methods such as ceil, floor, truncate, or round.
02504   */
02505 static VALUE
02506 BigDecimal_limit(int argc, VALUE *argv, VALUE self)
02507 {
02508     VALUE  nFig;
02509     VALUE  nCur = INT2NUM(VpGetPrecLimit());
02510 
02511     if(rb_scan_args(argc,argv,"01",&nFig)==1) {
02512         int nf;
02513         if(nFig==Qnil) return nCur;
02514         Check_Type(nFig, T_FIXNUM);
02515         nf = FIX2INT(nFig);
02516         if(nf<0) {
02517             rb_raise(rb_eArgError, "argument must be positive");
02518         }
02519         VpSetPrecLimit(nf);
02520     }
02521     return nCur;
02522 }
02523 
02524 /* Returns the sign of the value.
02525  *
02526  * Returns a positive value if > 0, a negative value if < 0, and a
02527  * zero if == 0.
02528  *
02529  * The specific value returned indicates the type and sign of the BigDecimal,
02530  * as follows:
02531  *
02532  * BigDecimal::SIGN_NaN:: value is Not a Number
02533  * BigDecimal::SIGN_POSITIVE_ZERO:: value is +0
02534  * BigDecimal::SIGN_NEGATIVE_ZERO:: value is -0
02535  * BigDecimal::SIGN_POSITIVE_INFINITE:: value is +infinity
02536  * BigDecimal::SIGN_NEGATIVE_INFINITE:: value is -infinity
02537  * BigDecimal::SIGN_POSITIVE_FINITE:: value is positive
02538  * BigDecimal::SIGN_NEGATIVE_FINITE:: value is negative
02539  */
02540 static VALUE
02541 BigDecimal_sign(VALUE self)
02542 { /* sign */
02543     int s = GetVpValue(self,1)->sign;
02544     return INT2FIX(s);
02545 }
02546 
02547 /*
02548  * call-seq: BigDecimal.save_exception_mode { ... }
02549  *
02550  * Excecute the provided block, but preserve the exception mode
02551  *
02552  *     BigDecimal.save_exception_mode do
02553  *       BigDecimal.mode(BigDecimal::EXCEPTION_OVERFLOW, false)
02554  *       BigDecimal.mode(BigDecimal::EXCEPTION_NaN, false)
02555  *
02556  *       BigDecimal.new(BigDecimal('Infinity'))
02557  *       BigDecimal.new(BigDecimal('-Infinity'))
02558  *       BigDecimal(BigDecimal.new('NaN'))
02559  *     end
02560  *
02561  * For use with the BigDecimal::EXCEPTION_*
02562  *
02563  * See BigDecimal.mode
02564  */
02565 static VALUE
02566 BigDecimal_save_exception_mode(VALUE self)
02567 {
02568     unsigned short const exception_mode = VpGetException();
02569     int state;
02570     VALUE ret = rb_protect(rb_yield, Qnil, &state);
02571     VpSetException(exception_mode);
02572     if (state) rb_jump_tag(state);
02573     return ret;
02574 }
02575 
02576 /*
02577  * call-seq: BigDecimal.save_rounding_mode { ... }
02578  *
02579  * Excecute the provided block, but preserve the rounding mode
02580  *
02581  *     BigDecimal.save_exception_mode do
02582  *       BigDecimal.mode(BigDecimal::ROUND_MODE, :up)
02583  *       puts BigDecimal.mode(BigDecimal::ROUND_MODE)
02584  *     end
02585  *
02586  * For use with the BigDecimal::ROUND_*
02587  *
02588  * See BigDecimal.mode
02589  */
02590 static VALUE
02591 BigDecimal_save_rounding_mode(VALUE self)
02592 {
02593     unsigned short const round_mode = VpGetRoundMode();
02594     int state;
02595     VALUE ret = rb_protect(rb_yield, Qnil, &state);
02596     VpSetRoundMode(round_mode);
02597     if (state) rb_jump_tag(state);
02598     return ret;
02599 }
02600 
02601 /*
02602  * call-seq: BigDecimal.save_limit { ... }
02603  *
02604  * Excecute the provided block, but preserve the precision limit
02605  *
02606  *      BigDecimal.limit(100)
02607  *      puts BigDecimal.limit
02608  *      BigDecimal.save_limit do
02609  *          BigDecimal.limit(200)
02610  *          puts BigDecimal.limit
02611  *      end
02612  *      puts BigDecimal.limit
02613  *
02614  */
02615 static VALUE
02616 BigDecimal_save_limit(VALUE self)
02617 {
02618     size_t const limit = VpGetPrecLimit();
02619     int state;
02620     VALUE ret = rb_protect(rb_yield, Qnil, &state);
02621     VpSetPrecLimit(limit);
02622     if (state) rb_jump_tag(state);
02623     return ret;
02624 }
02625 
02626 /* call-seq:
02627  * BigMath.exp(x, prec)
02628  *
02629  * Computes the value of e (the base of natural logarithms) raised to the
02630  * power of x, to the specified number of digits of precision.
02631  *
02632  * If x is infinity, returns Infinity.
02633  *
02634  * If x is NaN, returns NaN.
02635  */
02636 static VALUE
02637 BigMath_s_exp(VALUE klass, VALUE x, VALUE vprec)
02638 {
02639     ssize_t prec, n, i;
02640     Real* vx = NULL;
02641     VALUE one, d, x1, y, z;
02642     int negative = 0;
02643     int infinite = 0;
02644     int nan = 0;
02645     double flo;
02646 
02647     prec = NUM2SSIZET(vprec);
02648     if (prec <= 0) {
02649         rb_raise(rb_eArgError, "Zero or negative precision for exp");
02650     }
02651 
02652     /* TODO: the following switch statement is almostly the same as one in the
02653      *       BigDecimalCmp function. */
02654     switch (TYPE(x)) {
02655       case T_DATA:
02656           if (!is_kind_of_BigDecimal(x)) break;
02657           vx = DATA_PTR(x);
02658           negative = VpGetSign(vx) < 0;
02659           infinite = VpIsPosInf(vx) || VpIsNegInf(vx);
02660           nan = VpIsNaN(vx);
02661           break;
02662 
02663       case T_FIXNUM:
02664           /* fall through */
02665       case T_BIGNUM:
02666           vx = GetVpValue(x, 0);
02667           break;
02668 
02669       case T_FLOAT:
02670         flo = RFLOAT_VALUE(x);
02671         negative = flo < 0;
02672         infinite = isinf(flo);
02673         nan = isnan(flo);
02674         if (!infinite && !nan) {
02675             vx = GetVpValueWithPrec(x, DBL_DIG+1, 0);
02676         }
02677         break;
02678 
02679       case T_RATIONAL:
02680         vx = GetVpValueWithPrec(x, prec, 0);
02681         break;
02682 
02683       default:
02684         break;
02685     }
02686     if (infinite) {
02687         if (negative) {
02688             return ToValue(GetVpValueWithPrec(INT2NUM(0), prec, 1));
02689         }
02690         else {
02691             Real* vy;
02692             vy = VpCreateRbObject(prec, "#0");
02693             RB_GC_GUARD(vy->obj);
02694             VpSetInf(vy, VP_SIGN_POSITIVE_INFINITE);
02695             return ToValue(vy);
02696         }
02697     }
02698     else if (nan) {
02699         Real* vy;
02700         vy = VpCreateRbObject(prec, "#0");
02701         RB_GC_GUARD(vy->obj);
02702         VpSetNaN(vy);
02703         return ToValue(vy);
02704     }
02705     else if (vx == NULL) {
02706         cannot_be_coerced_into_BigDecimal(rb_eArgError, x);
02707     }
02708     x = RB_GC_GUARD(vx->obj);
02709 
02710     n = prec + rmpd_double_figures();
02711     negative = VpGetSign(vx) < 0;
02712     if (negative) {
02713         VpSetSign(vx, 1);
02714     }
02715 
02716     RB_GC_GUARD(one) = ToValue(VpCreateRbObject(1, "1"));
02717     RB_GC_GUARD(x1) = one;
02718     RB_GC_GUARD(y)  = one;
02719     RB_GC_GUARD(d)  = y;
02720     RB_GC_GUARD(z)  = one;
02721     i  = 0;
02722 
02723     while (!VpIsZero((Real*)DATA_PTR(d))) {
02724         VALUE argv[2];
02725         SIGNED_VALUE const ey = VpExponent10(DATA_PTR(y));
02726         SIGNED_VALUE const ed = VpExponent10(DATA_PTR(d));
02727         ssize_t m = n - vabs(ey - ed);
02728         if (m <= 0) {
02729             break;
02730         }
02731         else if ((size_t)m < rmpd_double_figures()) {
02732             m = rmpd_double_figures();
02733         }
02734 
02735         x1 = BigDecimal_mult2(x1, x, SSIZET2NUM(n));
02736         ++i;
02737         z = BigDecimal_mult(z, SSIZET2NUM(i));
02738         argv[0] = z;
02739         argv[1] = SSIZET2NUM(m);
02740         d = BigDecimal_div2(2, argv, x1);
02741         y = BigDecimal_add(y, d);
02742     }
02743 
02744     if (negative) {
02745         VALUE argv[2];
02746         argv[0] = y;
02747         argv[1] = vprec;
02748         return BigDecimal_div2(2, argv, one);
02749     }
02750     else {
02751         vprec = SSIZET2NUM(prec - VpExponent10(DATA_PTR(y)));
02752         return BigDecimal_round(1, &vprec, y);
02753     }
02754 }
02755 
02756 /* call-seq:
02757  * BigMath.log(x, prec)
02758  *
02759  * Computes the natural logarithm of x to the specified number of digits of
02760  * precision.
02761  *
02762  * If x is zero or negative, raises Math::DomainError.
02763  *
02764  * If x is positive infinity, returns Infinity.
02765  *
02766  * If x is NaN, returns NaN.
02767  */
02768 static VALUE
02769 BigMath_s_log(VALUE klass, VALUE x, VALUE vprec)
02770 {
02771     ssize_t prec, n, i;
02772     SIGNED_VALUE expo;
02773     Real* vx = NULL;
02774     VALUE argv[2], vn, one, two, w, x2, y, d;
02775     int zero = 0;
02776     int negative = 0;
02777     int infinite = 0;
02778     int nan = 0;
02779     double flo;
02780     long fix;
02781 
02782     if (!is_integer(vprec)) {
02783         rb_raise(rb_eArgError, "precision must be an Integer");
02784     }
02785 
02786     prec = NUM2SSIZET(vprec);
02787     if (prec <= 0) {
02788         rb_raise(rb_eArgError, "Zero or negative precision for exp");
02789     }
02790 
02791     /* TODO: the following switch statement is almostly the same as one in the
02792      *       BigDecimalCmp function. */
02793     switch (TYPE(x)) {
02794       case T_DATA:
02795           if (!is_kind_of_BigDecimal(x)) break;
02796           vx = DATA_PTR(x);
02797           zero = VpIsZero(vx);
02798           negative = VpGetSign(vx) < 0;
02799           infinite = VpIsPosInf(vx) || VpIsNegInf(vx);
02800           nan = VpIsNaN(vx);
02801           break;
02802 
02803       case T_FIXNUM:
02804         fix = FIX2LONG(x);
02805         zero = fix == 0;
02806         negative = fix < 0;
02807         goto get_vp_value;
02808 
02809       case T_BIGNUM:
02810         zero = RBIGNUM_ZERO_P(x);
02811         negative = RBIGNUM_NEGATIVE_P(x);
02812 get_vp_value:
02813         if (zero || negative) break;
02814         vx = GetVpValue(x, 0);
02815         break;
02816 
02817       case T_FLOAT:
02818         flo = RFLOAT_VALUE(x);
02819         zero = flo == 0;
02820         negative = flo < 0;
02821         infinite = isinf(flo);
02822         nan = isnan(flo);
02823         if (!zero && !negative && !infinite && !nan) {
02824             vx = GetVpValueWithPrec(x, DBL_DIG+1, 1);
02825         }
02826         break;
02827 
02828       case T_RATIONAL:
02829         zero = RRATIONAL_ZERO_P(x);
02830         negative = RRATIONAL_NEGATIVE_P(x);
02831         if (zero || negative) break;
02832         vx = GetVpValueWithPrec(x, prec, 1);
02833         break;
02834 
02835       case T_COMPLEX:
02836         rb_raise(rb_eMathDomainError,
02837                  "Complex argument for BigMath.log");
02838 
02839       default:
02840         break;
02841     }
02842     if (infinite && !negative) {
02843         Real* vy;
02844         vy = VpCreateRbObject(prec, "#0");
02845         RB_GC_GUARD(vy->obj);
02846         VpSetInf(vy, VP_SIGN_POSITIVE_INFINITE);
02847         return ToValue(vy);
02848     }
02849     else if (nan) {
02850         Real* vy;
02851         vy = VpCreateRbObject(prec, "#0");
02852         RB_GC_GUARD(vy->obj);
02853         VpSetNaN(vy);
02854         return ToValue(vy);
02855     }
02856     else if (zero || negative) {
02857         rb_raise(rb_eMathDomainError,
02858                  "Zero or negative argument for log");
02859     }
02860     else if (vx == NULL) {
02861         cannot_be_coerced_into_BigDecimal(rb_eArgError, x);
02862     }
02863     x = ToValue(vx);
02864 
02865     RB_GC_GUARD(one) = ToValue(VpCreateRbObject(1, "1"));
02866     RB_GC_GUARD(two) = ToValue(VpCreateRbObject(1, "2"));
02867 
02868     n = prec + rmpd_double_figures();
02869     RB_GC_GUARD(vn) = SSIZET2NUM(n);
02870     expo = VpExponent10(vx);
02871     if (expo < 0 || expo >= 3) {
02872         char buf[16];
02873         snprintf(buf, 16, "1E%"PRIdVALUE, -expo);
02874         x = BigDecimal_mult2(x, ToValue(VpCreateRbObject(1, buf)), vn);
02875     }
02876     else {
02877         expo = 0;
02878     }
02879     w = BigDecimal_sub(x, one);
02880     argv[0] = BigDecimal_add(x, one);
02881     argv[1] = vn;
02882     x = BigDecimal_div2(2, argv, w);
02883     RB_GC_GUARD(x2) = BigDecimal_mult2(x, x, vn);
02884     RB_GC_GUARD(y)  = x;
02885     RB_GC_GUARD(d)  = y;
02886     i = 1;
02887     while (!VpIsZero((Real*)DATA_PTR(d))) {
02888         SIGNED_VALUE const ey = VpExponent10(DATA_PTR(y));
02889         SIGNED_VALUE const ed = VpExponent10(DATA_PTR(d));
02890         ssize_t m = n - vabs(ey - ed);
02891         if (m <= 0) {
02892             break;
02893         }
02894         else if ((size_t)m < rmpd_double_figures()) {
02895             m = rmpd_double_figures();
02896         }
02897 
02898         x = BigDecimal_mult2(x2, x, vn);
02899         i += 2;
02900         argv[0] = SSIZET2NUM(i);
02901         argv[1] = SSIZET2NUM(m);
02902         d = BigDecimal_div2(2, argv, x);
02903         y = BigDecimal_add(y, d);
02904     }
02905 
02906     y = BigDecimal_mult(y, two);
02907     if (expo != 0) {
02908         VALUE log10, vexpo, dy;
02909         log10 = BigMath_s_log(klass, INT2FIX(10), vprec);
02910         vexpo = ToValue(GetVpValue(SSIZET2NUM(expo), 1));
02911         dy = BigDecimal_mult(log10, vexpo);
02912         y = BigDecimal_add(y, dy);
02913     }
02914 
02915     return y;
02916 }
02917 
02918 /* Document-class: BigDecimal
02919  * BigDecimal provides arbitrary-precision floating point decimal arithmetic.
02920  *
02921  * Copyright (C) 2002 by Shigeo Kobayashi <shigeo@tinyforest.gr.jp>.
02922  *
02923  * You may distribute under the terms of either the GNU General Public
02924  * License or the Artistic License, as specified in the README file
02925  * of the BigDecimal distribution.
02926  *
02927  * Documented by mathew <meta@pobox.com>.
02928  *
02929  * = Introduction
02930  *
02931  * Ruby provides built-in support for arbitrary precision integer arithmetic.
02932  *
02933  * For example:
02934  *
02935  *      42**13  #=>   1265437718438866624512
02936  *
02937  * BigDecimal provides similar support for very large or very accurate floating
02938  * point numbers.
02939  *
02940  * Decimal arithmetic is also useful for general calculation, because it
02941  * provides the correct answers people expect--whereas normal binary floating
02942  * point arithmetic often introduces subtle errors because of the conversion
02943  * between base 10 and base 2.
02944  *
02945  * For example, try:
02946  *
02947  *   sum = 0
02948  *   for i in (1..10000)
02949  *     sum = sum + 0.0001
02950  *   end
02951  *   print sum #=> 0.9999999999999062
02952  *
02953  * and contrast with the output from:
02954  *
02955  *   require 'bigdecimal'
02956  *
02957  *   sum = BigDecimal.new("0")
02958  *   for i in (1..10000)
02959  *     sum = sum + BigDecimal.new("0.0001")
02960  *   end
02961  *   print sum #=> 0.1E1
02962  *
02963  * Similarly:
02964  *
02965  *      (BigDecimal.new("1.2") - BigDecimal("1.0")) == BigDecimal("0.2") #=> true
02966  *
02967  *      (1.2 - 1.0) == 0.2 #=> false
02968  *
02969  * = Special features of accurate decimal arithmetic
02970  *
02971  * Because BigDecimal is more accurate than normal binary floating point
02972  * arithmetic, it requires some special values.
02973  *
02974  * == Infinity
02975  *
02976  * BigDecimal sometimes needs to return infinity, for example if you divide
02977  * a value by zero.
02978  *
02979  *      BigDecimal.new("1.0") / BigDecimal.new("0.0")  #=> infinity
02980  *      BigDecimal.new("-1.0") / BigDecimal.new("0.0")  #=> -infinity
02981  *
02982  * You can represent infinite numbers to BigDecimal using the strings
02983  * <code>'Infinity'</code>, <code>'+Infinity'</code> and
02984  * <code>'-Infinity'</code> (case-sensitive)
02985  *
02986  * == Not a Number
02987  *
02988  * When a computation results in an undefined value, the special value +NaN+
02989  * (for 'not a number') is returned.
02990  *
02991  * Example:
02992  *
02993  *      BigDecimal.new("0.0") / BigDecimal.new("0.0") #=> NaN
02994  *
02995  * You can also create undefined values.
02996  *
02997  * NaN is never considered to be the same as any other value, even NaN itself:
02998  *
02999  *      n = BigDecimal.new('NaN')
03000  *      n == 0.0 #=> nil
03001  *      n == n #=> nil
03002  *
03003  * == Positive and negative zero
03004  *
03005  * If a computation results in a value which is too small to be represented as
03006  * a BigDecimal within the currently specified limits of precision, zero must
03007  * be returned.
03008  *
03009  * If the value which is too small to be represented is negative, a BigDecimal
03010  * value of negative zero is returned.
03011  *
03012  *      BigDecimal.new("1.0") / BigDecimal.new("-Infinity") #=> -0.0
03013  *
03014  * If the value is positive, a value of positive zero is returned.
03015  *
03016  *      BigDecimal.new("1.0") / BigDecimal.new("Infinity") #=> 0.0
03017  *
03018  * (See BigDecimal.mode for how to specify limits of precision.)
03019  *
03020  * Note that +-0.0+ and +0.0+ are considered to be the same for the purposes of
03021  * comparison.
03022  *
03023  * Note also that in mathematics, there is no particular concept of negative
03024  * or positive zero; true mathematical zero has no sign.
03025  */
03026 void
03027 Init_bigdecimal(void)
03028 {
03029     VALUE arg;
03030 
03031     id_BigDecimal_exception_mode = rb_intern_const("BigDecimal.exception_mode");
03032     id_BigDecimal_rounding_mode = rb_intern_const("BigDecimal.rounding_mode");
03033     id_BigDecimal_precision_limit = rb_intern_const("BigDecimal.precision_limit");
03034 
03035     /* Initialize VP routines */
03036     VpInit(0UL);
03037 
03038     /* Class and method registration */
03039     rb_cBigDecimal = rb_define_class("BigDecimal",rb_cNumeric);
03040     rb_define_alloc_func(rb_cBigDecimal, BigDecimal_s_allocate);
03041 
03042     /* Global function */
03043     rb_define_global_function("BigDecimal", BigDecimal_global_new, -1);
03044 
03045     /* Class methods */
03046     rb_define_singleton_method(rb_cBigDecimal, "mode", BigDecimal_mode, -1);
03047     rb_define_singleton_method(rb_cBigDecimal, "limit", BigDecimal_limit, -1);
03048     rb_define_singleton_method(rb_cBigDecimal, "double_fig", BigDecimal_double_fig, 0);
03049     rb_define_singleton_method(rb_cBigDecimal, "_load", BigDecimal_load, 1);
03050     rb_define_singleton_method(rb_cBigDecimal, "ver", BigDecimal_version, 0);
03051 
03052     rb_define_singleton_method(rb_cBigDecimal, "save_exception_mode", BigDecimal_save_exception_mode, 0);
03053     rb_define_singleton_method(rb_cBigDecimal, "save_rounding_mode", BigDecimal_save_rounding_mode, 0);
03054     rb_define_singleton_method(rb_cBigDecimal, "save_limit", BigDecimal_save_limit, 0);
03055 
03056     /* Constants definition */
03057 
03058     /*
03059      * Base value used in internal calculations.  On a 32 bit system, BASE
03060      * is 10000, indicating that calculation is done in groups of 4 digits.
03061      * (If it were larger, BASE**2 wouldn't fit in 32 bits, so you couldn't
03062      * guarantee that two groups could always be multiplied together without
03063      * overflow.)
03064      */
03065     rb_define_const(rb_cBigDecimal, "BASE", INT2FIX((SIGNED_VALUE)VpBaseVal()));
03066 
03067     /* Exceptions */
03068 
03069     /*
03070      * 0xff: Determines whether overflow, underflow or zero divide result in
03071      * an exception being thrown. See BigDecimal.mode.
03072      */
03073     rb_define_const(rb_cBigDecimal, "EXCEPTION_ALL",INT2FIX(VP_EXCEPTION_ALL));
03074 
03075     /*
03076      * 0x02: Determines what happens when the result of a computation is not a
03077      * number (NaN). See BigDecimal.mode.
03078      */
03079     rb_define_const(rb_cBigDecimal, "EXCEPTION_NaN",INT2FIX(VP_EXCEPTION_NaN));
03080 
03081     /*
03082      * 0x01: Determines what happens when the result of a computation is
03083      * infinity.  See BigDecimal.mode.
03084      */
03085     rb_define_const(rb_cBigDecimal, "EXCEPTION_INFINITY",INT2FIX(VP_EXCEPTION_INFINITY));
03086 
03087     /*
03088      * 0x04: Determines what happens when the result of a computation is an
03089      * underflow (a result too small to be represented). See BigDecimal.mode.
03090      */
03091     rb_define_const(rb_cBigDecimal, "EXCEPTION_UNDERFLOW",INT2FIX(VP_EXCEPTION_UNDERFLOW));
03092 
03093     /*
03094      * 0x01: Determines what happens when the result of a computation is an
03095      * overflow (a result too large to be represented). See BigDecimal.mode.
03096      */
03097     rb_define_const(rb_cBigDecimal, "EXCEPTION_OVERFLOW",INT2FIX(VP_EXCEPTION_OVERFLOW));
03098 
03099     /*
03100      * 0x01: Determines what happens when a division by zero is performed.
03101      * See BigDecimal.mode.
03102      */
03103     rb_define_const(rb_cBigDecimal, "EXCEPTION_ZERODIVIDE",INT2FIX(VP_EXCEPTION_ZERODIVIDE));
03104 
03105     /*
03106      * 0x100: Determines what happens when a result must be rounded in order to
03107      * fit in the appropriate number of significant digits. See
03108      * BigDecimal.mode.
03109      */
03110     rb_define_const(rb_cBigDecimal, "ROUND_MODE",INT2FIX(VP_ROUND_MODE));
03111 
03112     /* 1: Indicates that values should be rounded away from zero. See
03113      * BigDecimal.mode.
03114      */
03115     rb_define_const(rb_cBigDecimal, "ROUND_UP",INT2FIX(VP_ROUND_UP));
03116 
03117     /* 2: Indicates that values should be rounded towards zero. See
03118      * BigDecimal.mode.
03119      */
03120     rb_define_const(rb_cBigDecimal, "ROUND_DOWN",INT2FIX(VP_ROUND_DOWN));
03121 
03122     /* 3: Indicates that digits >= 5 should be rounded up, others rounded down.
03123      * See BigDecimal.mode. */
03124     rb_define_const(rb_cBigDecimal, "ROUND_HALF_UP",INT2FIX(VP_ROUND_HALF_UP));
03125 
03126     /* 4: Indicates that digits >= 6 should be rounded up, others rounded down.
03127      * See BigDecimal.mode.
03128      */
03129     rb_define_const(rb_cBigDecimal, "ROUND_HALF_DOWN",INT2FIX(VP_ROUND_HALF_DOWN));
03130     /* 5: Round towards +infinity. See BigDecimal.mode. */
03131     rb_define_const(rb_cBigDecimal, "ROUND_CEILING",INT2FIX(VP_ROUND_CEIL));
03132 
03133     /* 6: Round towards -infinity. See BigDecimal.mode. */
03134     rb_define_const(rb_cBigDecimal, "ROUND_FLOOR",INT2FIX(VP_ROUND_FLOOR));
03135 
03136     /* 7: Round towards the even neighbor. See BigDecimal.mode. */
03137     rb_define_const(rb_cBigDecimal, "ROUND_HALF_EVEN",INT2FIX(VP_ROUND_HALF_EVEN));
03138 
03139     /* 0: Indicates that a value is not a number. See BigDecimal.sign. */
03140     rb_define_const(rb_cBigDecimal, "SIGN_NaN",INT2FIX(VP_SIGN_NaN));
03141 
03142     /* 1: Indicates that a value is +0. See BigDecimal.sign. */
03143     rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_ZERO",INT2FIX(VP_SIGN_POSITIVE_ZERO));
03144 
03145     /* -1: Indicates that a value is -0. See BigDecimal.sign. */
03146     rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_ZERO",INT2FIX(VP_SIGN_NEGATIVE_ZERO));
03147 
03148     /* 2: Indicates that a value is positive and finite. See BigDecimal.sign. */
03149     rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_FINITE",INT2FIX(VP_SIGN_POSITIVE_FINITE));
03150 
03151     /* -2: Indicates that a value is negative and finite. See BigDecimal.sign. */
03152     rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_FINITE",INT2FIX(VP_SIGN_NEGATIVE_FINITE));
03153 
03154     /* 3: Indicates that a value is positive and infinite. See BigDecimal.sign. */
03155     rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_INFINITE",INT2FIX(VP_SIGN_POSITIVE_INFINITE));
03156 
03157     /* -3: Indicates that a value is negative and infinite. See BigDecimal.sign. */
03158     rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_INFINITE",INT2FIX(VP_SIGN_NEGATIVE_INFINITE));
03159 
03160     arg = rb_str_new2("+Infinity");
03161     /* Positive infinity value. */
03162     rb_define_const(rb_cBigDecimal, "INFINITY", BigDecimal_global_new(1, &arg, rb_cBigDecimal));
03163     arg = rb_str_new2("NaN");
03164     /* 'Not a Number' value. */
03165     rb_define_const(rb_cBigDecimal, "NAN", BigDecimal_global_new(1, &arg, rb_cBigDecimal));
03166 
03167 
03168     /* instance methods */
03169     rb_define_method(rb_cBigDecimal, "initialize", BigDecimal_initialize, -1);
03170     rb_define_method(rb_cBigDecimal, "initialize_copy", BigDecimal_initialize_copy, 1);
03171     rb_define_method(rb_cBigDecimal, "precs", BigDecimal_prec, 0);
03172 
03173     rb_define_method(rb_cBigDecimal, "add", BigDecimal_add2, 2);
03174     rb_define_method(rb_cBigDecimal, "sub", BigDecimal_sub2, 2);
03175     rb_define_method(rb_cBigDecimal, "mult", BigDecimal_mult2, 2);
03176     rb_define_method(rb_cBigDecimal, "div", BigDecimal_div2, -1);
03177     rb_define_method(rb_cBigDecimal, "hash", BigDecimal_hash, 0);
03178     rb_define_method(rb_cBigDecimal, "to_s", BigDecimal_to_s, -1);
03179     rb_define_method(rb_cBigDecimal, "to_i", BigDecimal_to_i, 0);
03180     rb_define_method(rb_cBigDecimal, "to_int", BigDecimal_to_i, 0);
03181     rb_define_method(rb_cBigDecimal, "to_r", BigDecimal_to_r, 0);
03182     rb_define_method(rb_cBigDecimal, "split", BigDecimal_split, 0);
03183     rb_define_method(rb_cBigDecimal, "+", BigDecimal_add, 1);
03184     rb_define_method(rb_cBigDecimal, "-", BigDecimal_sub, 1);
03185     rb_define_method(rb_cBigDecimal, "+@", BigDecimal_uplus, 0);
03186     rb_define_method(rb_cBigDecimal, "-@", BigDecimal_neg, 0);
03187     rb_define_method(rb_cBigDecimal, "*", BigDecimal_mult, 1);
03188     rb_define_method(rb_cBigDecimal, "/", BigDecimal_div, 1);
03189     rb_define_method(rb_cBigDecimal, "quo", BigDecimal_div, 1);
03190     rb_define_method(rb_cBigDecimal, "%", BigDecimal_mod, 1);
03191     rb_define_method(rb_cBigDecimal, "modulo", BigDecimal_mod, 1);
03192     rb_define_method(rb_cBigDecimal, "remainder", BigDecimal_remainder, 1);
03193     rb_define_method(rb_cBigDecimal, "divmod", BigDecimal_divmod, 1);
03194     /* rb_define_method(rb_cBigDecimal, "dup", BigDecimal_dup, 0); */
03195     rb_define_method(rb_cBigDecimal, "to_f", BigDecimal_to_f, 0);
03196     rb_define_method(rb_cBigDecimal, "abs", BigDecimal_abs, 0);
03197     rb_define_method(rb_cBigDecimal, "sqrt", BigDecimal_sqrt, 1);
03198     rb_define_method(rb_cBigDecimal, "fix", BigDecimal_fix, 0);
03199     rb_define_method(rb_cBigDecimal, "round", BigDecimal_round, -1);
03200     rb_define_method(rb_cBigDecimal, "frac", BigDecimal_frac, 0);
03201     rb_define_method(rb_cBigDecimal, "floor", BigDecimal_floor, -1);
03202     rb_define_method(rb_cBigDecimal, "ceil", BigDecimal_ceil, -1);
03203     rb_define_method(rb_cBigDecimal, "power", BigDecimal_power, -1);
03204     rb_define_method(rb_cBigDecimal, "**", BigDecimal_power_op, 1);
03205     rb_define_method(rb_cBigDecimal, "<=>", BigDecimal_comp, 1);
03206     rb_define_method(rb_cBigDecimal, "==", BigDecimal_eq, 1);
03207     rb_define_method(rb_cBigDecimal, "===", BigDecimal_eq, 1);
03208     rb_define_method(rb_cBigDecimal, "eql?", BigDecimal_eq, 1);
03209     rb_define_method(rb_cBigDecimal, "<", BigDecimal_lt, 1);
03210     rb_define_method(rb_cBigDecimal, "<=", BigDecimal_le, 1);
03211     rb_define_method(rb_cBigDecimal, ">", BigDecimal_gt, 1);
03212     rb_define_method(rb_cBigDecimal, ">=", BigDecimal_ge, 1);
03213     rb_define_method(rb_cBigDecimal, "zero?", BigDecimal_zero, 0);
03214     rb_define_method(rb_cBigDecimal, "nonzero?", BigDecimal_nonzero, 0);
03215     rb_define_method(rb_cBigDecimal, "coerce", BigDecimal_coerce, 1);
03216     rb_define_method(rb_cBigDecimal, "inspect", BigDecimal_inspect, 0);
03217     rb_define_method(rb_cBigDecimal, "exponent", BigDecimal_exponent, 0);
03218     rb_define_method(rb_cBigDecimal, "sign", BigDecimal_sign, 0);
03219     rb_define_method(rb_cBigDecimal, "nan?",      BigDecimal_IsNaN, 0);
03220     rb_define_method(rb_cBigDecimal, "infinite?", BigDecimal_IsInfinite, 0);
03221     rb_define_method(rb_cBigDecimal, "finite?",   BigDecimal_IsFinite, 0);
03222     rb_define_method(rb_cBigDecimal, "truncate",  BigDecimal_truncate, -1);
03223     rb_define_method(rb_cBigDecimal, "_dump", BigDecimal_dump, -1);
03224 
03225     /* mathematical functions */
03226     rb_mBigMath = rb_define_module("BigMath");
03227     rb_define_singleton_method(rb_mBigMath, "exp", BigMath_s_exp, 2);
03228     rb_define_singleton_method(rb_mBigMath, "log", BigMath_s_log, 2);
03229 
03230     id_up = rb_intern_const("up");
03231     id_down = rb_intern_const("down");
03232     id_truncate = rb_intern_const("truncate");
03233     id_half_up = rb_intern_const("half_up");
03234     id_default = rb_intern_const("default");
03235     id_half_down = rb_intern_const("half_down");
03236     id_half_even = rb_intern_const("half_even");
03237     id_banker = rb_intern_const("banker");
03238     id_ceiling = rb_intern_const("ceiling");
03239     id_ceil = rb_intern_const("ceil");
03240     id_floor = rb_intern_const("floor");
03241     id_to_r = rb_intern_const("to_r");
03242     id_eq = rb_intern_const("==");
03243 }
03244 
03245 /*
03246  *
03247  *  ============================================================================
03248  *
03249  *  vp_ routines begin from here.
03250  *
03251  *  ============================================================================
03252  *
03253  */
03254 #ifdef BIGDECIMAL_DEBUG
03255 static int gfDebug = 1;         /* Debug switch */
03256 #if 0
03257 static int gfCheckVal = 1;      /* Value checking flag in VpNmlz()  */
03258 #endif
03259 #endif /* BIGDECIMAL_DEBUG */
03260 
03261 static Real *VpConstOne;    /* constant 1.0 */
03262 static Real *VpPt5;        /* constant 0.5 */
03263 #define maxnr 100UL    /* Maximum iterations for calcurating sqrt. */
03264                 /* used in VpSqrt() */
03265 
03266 /* ETC */
03267 #define MemCmp(x,y,z) memcmp(x,y,z)
03268 #define StrCmp(x,y)   strcmp(x,y)
03269 
03270 static int VpIsDefOP(Real *c,Real *a,Real *b,int sw);
03271 static int AddExponent(Real *a, SIGNED_VALUE n);
03272 static BDIGIT VpAddAbs(Real *a,Real *b,Real *c);
03273 static BDIGIT VpSubAbs(Real *a,Real *b,Real *c);
03274 static size_t VpSetPTR(Real *a, Real *b, Real *c, size_t *a_pos, size_t *b_pos, size_t *c_pos, BDIGIT *av, BDIGIT *bv);
03275 static int VpNmlz(Real *a);
03276 static void VpFormatSt(char *psz, size_t fFmt);
03277 static int VpRdup(Real *m, size_t ind_m);
03278 
03279 #ifdef BIGDECIMAL_DEBUG
03280 static int gnAlloc=0; /* Memory allocation counter */
03281 #endif /* BIGDECIMAL_DEBUG */
03282 
03283 VP_EXPORT void *
03284 VpMemAlloc(size_t mb)
03285 {
03286     void *p = xmalloc(mb);
03287     if (!p) {
03288         VpException(VP_EXCEPTION_MEMORY, "failed to allocate memory", 1);
03289     }
03290     memset(p, 0, mb);
03291 #ifdef BIGDECIMAL_DEBUG
03292     gnAlloc++; /* Count allocation call */
03293 #endif /* BIGDECIMAL_DEBUG */
03294     return p;
03295 }
03296 
03297 VP_EXPORT void *
03298 VpMemRealloc(void *ptr, size_t mb)
03299 {
03300     void *p = xrealloc(ptr, mb);
03301     if (!p) {
03302         VpException(VP_EXCEPTION_MEMORY, "failed to allocate memory", 1);
03303     }
03304     return p;
03305 }
03306 
03307 VP_EXPORT void
03308 VpFree(Real *pv)
03309 {
03310     if(pv != NULL) {
03311         xfree(pv);
03312 #ifdef BIGDECIMAL_DEBUG
03313         gnAlloc--; /* Decrement allocation count */
03314         if(gnAlloc==0) {
03315             printf(" *************** All memories allocated freed ****************");
03316             getchar();
03317         }
03318         if(gnAlloc<0) {
03319             printf(" ??????????? Too many memory free calls(%d) ?????????????\n",gnAlloc);
03320             getchar();
03321         }
03322 #endif /* BIGDECIMAL_DEBUG */
03323     }
03324 }
03325 
03326 /*
03327  * EXCEPTION Handling.
03328  */
03329 
03330 #define rmpd_set_thread_local_exception_mode(mode) \
03331     rb_thread_local_aset( \
03332         rb_thread_current(), \
03333         id_BigDecimal_exception_mode, \
03334         INT2FIX((int)(mode)) \
03335     )
03336 
03337 static unsigned short
03338 VpGetException (void)
03339 {
03340     VALUE const vmode = rb_thread_local_aref(
03341         rb_thread_current(),
03342         id_BigDecimal_exception_mode
03343     );
03344 
03345     if (NIL_P(vmode)) {
03346         rmpd_set_thread_local_exception_mode(RMPD_EXCEPTION_MODE_DEFAULT);
03347         return RMPD_EXCEPTION_MODE_DEFAULT;
03348     }
03349 
03350     return (unsigned short)FIX2UINT(vmode);
03351 }
03352 
03353 static void
03354 VpSetException(unsigned short f)
03355 {
03356     rmpd_set_thread_local_exception_mode(f);
03357 }
03358 
03359 /*
03360  * Precision limit.
03361  */
03362 
03363 #define rmpd_set_thread_local_precision_limit(limit) \
03364     rb_thread_local_aset( \
03365         rb_thread_current(), \
03366         id_BigDecimal_precision_limit, \
03367         SIZET2NUM(limit) \
03368     )
03369 #define RMPD_PRECISION_LIMIT_DEFAULT ((size_t)0)
03370 
03371 /* These 2 functions added at v1.1.7 */
03372 VP_EXPORT size_t
03373 VpGetPrecLimit(void)
03374 {
03375     VALUE const vlimit = rb_thread_local_aref(
03376         rb_thread_current(),
03377         id_BigDecimal_precision_limit
03378     );
03379 
03380     if (NIL_P(vlimit)) {
03381         rmpd_set_thread_local_precision_limit(RMPD_PRECISION_LIMIT_DEFAULT);
03382         return RMPD_PRECISION_LIMIT_DEFAULT;
03383     }
03384 
03385     return NUM2SIZET(vlimit);
03386 }
03387 
03388 VP_EXPORT size_t
03389 VpSetPrecLimit(size_t n)
03390 {
03391     size_t const s = VpGetPrecLimit();
03392     rmpd_set_thread_local_precision_limit(n);
03393     return s;
03394 }
03395 
03396 /*
03397  * Rounding mode.
03398  */
03399 
03400 #define rmpd_set_thread_local_rounding_mode(mode) \
03401     rb_thread_local_aset( \
03402         rb_thread_current(), \
03403         id_BigDecimal_rounding_mode, \
03404         INT2FIX((int)(mode)) \
03405     )
03406 
03407 VP_EXPORT unsigned short
03408 VpGetRoundMode(void)
03409 {
03410     VALUE const vmode = rb_thread_local_aref(
03411         rb_thread_current(),
03412         id_BigDecimal_rounding_mode
03413     );
03414 
03415     if (NIL_P(vmode)) {
03416         rmpd_set_thread_local_rounding_mode(RMPD_ROUNDING_MODE_DEFAULT);
03417         return RMPD_ROUNDING_MODE_DEFAULT;
03418     }
03419 
03420     return (unsigned short)FIX2INT(vmode);
03421 }
03422 
03423 VP_EXPORT int
03424 VpIsRoundMode(unsigned short n)
03425 {
03426     switch (n) {
03427       case VP_ROUND_UP:
03428       case VP_ROUND_DOWN:
03429       case VP_ROUND_HALF_UP:
03430       case VP_ROUND_HALF_DOWN:
03431       case VP_ROUND_CEIL:
03432       case VP_ROUND_FLOOR:
03433       case VP_ROUND_HALF_EVEN:
03434         return 1;
03435 
03436       default:
03437         return 0;
03438     }
03439 }
03440 
03441 VP_EXPORT unsigned short
03442 VpSetRoundMode(unsigned short n)
03443 {
03444     if (VpIsRoundMode(n)) {
03445         rmpd_set_thread_local_rounding_mode(n);
03446         return n;
03447     }
03448 
03449     return VpGetRoundMode();
03450 }
03451 
03452 /*
03453  *  0.0 & 1.0 generator
03454  *    These gZero_..... and gOne_..... can be any name
03455  *    referenced from nowhere except Zero() and One().
03456  *    gZero_..... and gOne_..... must have global scope
03457  *    (to let the compiler know they may be changed in outside
03458  *    (... but not actually..)).
03459  */
03460 volatile const double gZero_ABCED9B1_CE73__00400511F31D = 0.0;
03461 volatile const double gOne_ABCED9B4_CE73__00400511F31D  = 1.0;
03462 static double
03463 Zero(void)
03464 {
03465     return gZero_ABCED9B1_CE73__00400511F31D;
03466 }
03467 
03468 static double
03469 One(void)
03470 {
03471     return gOne_ABCED9B4_CE73__00400511F31D;
03472 }
03473 
03474 /*
03475   ----------------------------------------------------------------
03476   Value of sign in Real structure is reserved for future use.
03477   short sign;
03478                     ==0 : NaN
03479                       1 : Positive zero
03480                      -1 : Negative zero
03481                       2 : Positive number
03482                      -2 : Negative number
03483                       3 : Positive infinite number
03484                      -3 : Negative infinite number
03485   ----------------------------------------------------------------
03486 */
03487 
03488 VP_EXPORT double
03489 VpGetDoubleNaN(void) /* Returns the value of NaN */
03490 {
03491     static double fNaN = 0.0;
03492     if(fNaN==0.0) fNaN = Zero()/Zero();
03493     return fNaN;
03494 }
03495 
03496 VP_EXPORT double
03497 VpGetDoublePosInf(void) /* Returns the value of +Infinity */
03498 {
03499     static double fInf = 0.0;
03500     if(fInf==0.0) fInf = One()/Zero();
03501     return fInf;
03502 }
03503 
03504 VP_EXPORT double
03505 VpGetDoubleNegInf(void) /* Returns the value of -Infinity */
03506 {
03507     static double fInf = 0.0;
03508     if(fInf==0.0) fInf = -(One()/Zero());
03509     return fInf;
03510 }
03511 
03512 VP_EXPORT double
03513 VpGetDoubleNegZero(void) /* Returns the value of -0 */
03514 {
03515     static double nzero = 1000.0;
03516     if(nzero!=0.0) nzero = (One()/VpGetDoubleNegInf());
03517     return nzero;
03518 }
03519 
03520 #if 0  /* unused */
03521 VP_EXPORT int
03522 VpIsNegDoubleZero(double v)
03523 {
03524     double z = VpGetDoubleNegZero();
03525     return MemCmp(&v,&z,sizeof(v))==0;
03526 }
03527 #endif
03528 
03529 VP_EXPORT int
03530 VpException(unsigned short f, const char *str,int always)
03531 {
03532     VALUE exc;
03533     int   fatal=0;
03534     unsigned short const exception_mode = VpGetException();
03535 
03536     if(f==VP_EXCEPTION_OP || f==VP_EXCEPTION_MEMORY) always = 1;
03537 
03538     if (always || (exception_mode & f)) {
03539         switch(f)
03540         {
03541         /*
03542         case VP_EXCEPTION_OVERFLOW:
03543         */
03544         case VP_EXCEPTION_ZERODIVIDE:
03545         case VP_EXCEPTION_INFINITY:
03546         case VP_EXCEPTION_NaN:
03547         case VP_EXCEPTION_UNDERFLOW:
03548         case VP_EXCEPTION_OP:
03549              exc = rb_eFloatDomainError;
03550              goto raise;
03551         case VP_EXCEPTION_MEMORY:
03552              fatal = 1;
03553              goto raise;
03554         default:
03555              fatal = 1;
03556              goto raise;
03557         }
03558     }
03559     return 0; /* 0 Means VpException() raised no exception */
03560 
03561 raise:
03562     if(fatal) rb_fatal("%s", str);
03563     else   rb_raise(exc, "%s", str);
03564     return 0;
03565 }
03566 
03567 /* Throw exception or returns 0,when resulting c is Inf or NaN */
03568 /*  sw=1:+ 2:- 3:* 4:/ */
03569 static int
03570 VpIsDefOP(Real *c,Real *a,Real *b,int sw)
03571 {
03572     if(VpIsNaN(a) || VpIsNaN(b)) {
03573         /* at least a or b is NaN */
03574         VpSetNaN(c);
03575         goto NaN;
03576     }
03577 
03578     if(VpIsInf(a)) {
03579         if(VpIsInf(b)) {
03580             switch(sw)
03581             {
03582             case 1: /* + */
03583                 if(VpGetSign(a)==VpGetSign(b)) {
03584                     VpSetInf(c,VpGetSign(a));
03585                     goto Inf;
03586                 } else {
03587                     VpSetNaN(c);
03588                     goto NaN;
03589                 }
03590             case 2: /* - */
03591                 if(VpGetSign(a)!=VpGetSign(b)) {
03592                     VpSetInf(c,VpGetSign(a));
03593                     goto Inf;
03594                 } else {
03595                     VpSetNaN(c);
03596                     goto NaN;
03597                 }
03598                 break;
03599             case 3: /* * */
03600                 VpSetInf(c,VpGetSign(a)*VpGetSign(b));
03601                 goto Inf;
03602                 break;
03603             case 4: /* / */
03604                 VpSetNaN(c);
03605                 goto NaN;
03606             }
03607             VpSetNaN(c);
03608             goto NaN;
03609         }
03610         /* Inf op Finite */
03611         switch(sw)
03612         {
03613         case 1: /* + */
03614         case 2: /* - */
03615                 VpSetInf(c,VpGetSign(a));
03616                 break;
03617         case 3: /* * */
03618                 if(VpIsZero(b)) {
03619                     VpSetNaN(c);
03620                     goto NaN;
03621                 }
03622                 VpSetInf(c,VpGetSign(a)*VpGetSign(b));
03623                 break;
03624         case 4: /* / */
03625                 VpSetInf(c,VpGetSign(a)*VpGetSign(b));
03626         }
03627         goto Inf;
03628     }
03629 
03630     if(VpIsInf(b)) {
03631         switch(sw)
03632         {
03633         case 1: /* + */
03634                 VpSetInf(c,VpGetSign(b));
03635                 break;
03636         case 2: /* - */
03637                 VpSetInf(c,-VpGetSign(b));
03638                 break;
03639         case 3: /* * */
03640                 if(VpIsZero(a)) {
03641                     VpSetNaN(c);
03642                     goto NaN;
03643                 }
03644                 VpSetInf(c,VpGetSign(a)*VpGetSign(b));
03645                 break;
03646         case 4: /* / */
03647                 VpSetZero(c,VpGetSign(a)*VpGetSign(b));
03648         }
03649         goto Inf;
03650     }
03651     return 1; /* Results OK */
03652 
03653 Inf:
03654     return VpException(VP_EXCEPTION_INFINITY,"Computation results to 'Infinity'",0);
03655 NaN:
03656     return VpException(VP_EXCEPTION_NaN,"Computation results to 'NaN'",0);
03657 }
03658 
03659 /*
03660   ----------------------------------------------------------------
03661 */
03662 
03663 /*
03664  *    returns number of chars needed to represent vp in specified format.
03665  */
03666 VP_EXPORT size_t
03667 VpNumOfChars(Real *vp,const char *pszFmt)
03668 {
03669     SIGNED_VALUE  ex;
03670     size_t nc;
03671 
03672     if(vp == NULL)   return BASE_FIG*2+6;
03673     if(!VpIsDef(vp)) return 32; /* not sure,may be OK */
03674 
03675     switch(*pszFmt)
03676     {
03677     case 'F':
03678          nc = BASE_FIG*(vp->Prec + 1)+2;
03679          ex = vp->exponent;
03680          if(ex < 0) {
03681              nc += BASE_FIG*(size_t)(-ex);
03682          }
03683          else {
03684              if((size_t)ex > vp->Prec) {
03685                  nc += BASE_FIG*((size_t)ex - vp->Prec);
03686              }
03687          }
03688          break;
03689     case 'E':
03690     default:
03691          nc = BASE_FIG*(vp->Prec + 2)+6; /* 3: sign + exponent chars */
03692     }
03693     return nc;
03694 }
03695 
03696 /*
03697  * Initializer for Vp routines and constants used.
03698  * [Input]
03699  *   BaseVal: Base value(assigned to BASE) for Vp calculation.
03700  *   It must be the form BaseVal=10**n.(n=1,2,3,...)
03701  *   If Base <= 0L,then the BASE will be calcurated so
03702  *   that BASE is as large as possible satisfying the
03703  *   relation MaxVal <= BASE*(BASE+1). Where the value
03704  *   MaxVal is the largest value which can be represented
03705  *   by one BDIGIT word in the computer used.
03706  *
03707  * [Returns]
03708  * 1+DBL_DIG   ... OK
03709  */
03710 VP_EXPORT size_t
03711 VpInit(BDIGIT BaseVal)
03712 {
03713     /* Setup +/- Inf  NaN -0 */
03714     VpGetDoubleNaN();
03715     VpGetDoublePosInf();
03716     VpGetDoubleNegInf();
03717     VpGetDoubleNegZero();
03718 
03719     /* Allocates Vp constants. */
03720     VpConstOne = VpAlloc(1UL, "1");
03721     VpPt5 = VpAlloc(1UL, ".5");
03722 
03723 #ifdef BIGDECIMAL_DEBUG
03724     gnAlloc = 0;
03725 #endif /* BIGDECIMAL_DEBUG */
03726 
03727 #ifdef BIGDECIMAL_DEBUG
03728     if(gfDebug) {
03729         printf("VpInit: BaseVal   = %lu\n", BaseVal);
03730         printf("  BASE   = %lu\n", BASE);
03731         printf("  HALF_BASE = %lu\n", HALF_BASE);
03732         printf("  BASE1  = %lu\n", BASE1);
03733         printf("  BASE_FIG  = %u\n", BASE_FIG);
03734         printf("  DBLE_FIG  = %d\n", DBLE_FIG);
03735     }
03736 #endif /* BIGDECIMAL_DEBUG */
03737 
03738     return rmpd_double_figures();
03739 }
03740 
03741 VP_EXPORT Real *
03742 VpOne(void)
03743 {
03744     return VpConstOne;
03745 }
03746 
03747 /* If exponent overflows,then raise exception or returns 0 */
03748 static int
03749 AddExponent(Real *a, SIGNED_VALUE n)
03750 {
03751     SIGNED_VALUE e = a->exponent;
03752     SIGNED_VALUE m = e+n;
03753     SIGNED_VALUE eb, mb;
03754     if(e>0) {
03755         if(n>0) {
03756             mb = m*(SIGNED_VALUE)BASE_FIG;
03757             eb = e*(SIGNED_VALUE)BASE_FIG;
03758             if(mb<eb) goto overflow;
03759         }
03760     } else if(n<0) {
03761         mb = m*(SIGNED_VALUE)BASE_FIG;
03762         eb = e*(SIGNED_VALUE)BASE_FIG;
03763         if(mb>eb) goto underflow;
03764     }
03765     a->exponent = m;
03766     return 1;
03767 
03768 /* Overflow/Underflow ==> Raise exception or returns 0 */
03769 underflow:
03770     VpSetZero(a,VpGetSign(a));
03771     return VpException(VP_EXCEPTION_UNDERFLOW,"Exponent underflow",0);
03772 
03773 overflow:
03774     VpSetInf(a,VpGetSign(a));
03775     return VpException(VP_EXCEPTION_OVERFLOW,"Exponent overflow",0);
03776 }
03777 
03778 /*
03779  * Allocates variable.
03780  * [Input]
03781  *   mx ... allocation unit, if zero then mx is determined by szVal.
03782  *    The mx is the number of effective digits can to be stored.
03783  *   szVal ... value assigned(char). If szVal==NULL,then zero is assumed.
03784  *            If szVal[0]=='#' then Max. Prec. will not be considered(1.1.7),
03785  *            full precision specified by szVal is allocated.
03786  *
03787  * [Returns]
03788  *   Pointer to the newly allocated variable, or
03789  *   NULL be returned if memory allocation is failed,or any error.
03790  */
03791 VP_EXPORT Real *
03792 VpAlloc(size_t mx, const char *szVal)
03793 {
03794     size_t i, ni, ipn, ipf, nf, ipe, ne, nalloc;
03795     char v,*psz;
03796     int  sign=1;
03797     Real *vp = NULL;
03798     size_t mf = VpGetPrecLimit();
03799     VALUE buf;
03800 
03801     mx = (mx + BASE_FIG - 1) / BASE_FIG + 1;    /* Determine allocation unit. */
03802     if (szVal) {
03803         while (ISSPACE(*szVal)) szVal++;
03804         if (*szVal != '#') {
03805              if (mf) {
03806                 mf = (mf + BASE_FIG - 1) / BASE_FIG + 2; /* Needs 1 more for div */
03807                 if (mx > mf) {
03808                     mx = mf;
03809                 }
03810             }
03811         }
03812         else {
03813             ++szVal;
03814         }
03815     }
03816     else {
03817        /* necessary to be able to store */
03818        /* at least mx digits. */
03819        /* szVal==NULL ==> allocate zero value. */
03820        vp = VpAllocReal(mx);
03821        /* xmalloc() alway returns(or throw interruption) */
03822        vp->MaxPrec = mx;    /* set max precision */
03823        VpSetZero(vp,1);    /* initialize vp to zero. */
03824        return vp;
03825     }
03826 
03827     /* Skip all '_' after digit: 2006-6-30 */
03828     ni = 0;
03829     buf = rb_str_tmp_new(strlen(szVal)+1);
03830     psz = RSTRING_PTR(buf);
03831     i   = 0;
03832     ipn = 0;
03833     while ((psz[i]=szVal[ipn]) != 0) {
03834         if (ISDIGIT(psz[i])) ++ni;
03835         if (psz[i] == '_') {
03836             if (ni > 0) { ipn++; continue; }
03837             psz[i] = 0;
03838             break;
03839         }
03840         ++i;
03841         ++ipn;
03842     }
03843     /* Skip trailing spaces */
03844     while (--i > 0) {
03845         if (ISSPACE(psz[i])) psz[i] = 0;
03846         else break;
03847     }
03848     szVal = psz;
03849 
03850     /* Check on Inf & NaN */
03851     if (StrCmp(szVal, SZ_PINF) == 0 ||
03852         StrCmp(szVal, SZ_INF)  == 0 ) {
03853         vp = VpAllocReal(1);
03854         vp->MaxPrec = 1;    /* set max precision */
03855         VpSetPosInf(vp);
03856         return vp;
03857     }
03858     if (StrCmp(szVal, SZ_NINF) == 0) {
03859         vp = VpAllocReal(1);
03860         vp->MaxPrec = 1;    /* set max precision */
03861         VpSetNegInf(vp);
03862         return vp;
03863     }
03864     if (StrCmp(szVal, SZ_NaN) == 0) {
03865         vp = VpAllocReal(1);
03866         vp->MaxPrec = 1;    /* set max precision */
03867         VpSetNaN(vp);
03868         return vp;
03869     }
03870 
03871     /* check on number szVal[] */
03872     ipn = i = 0;
03873     if      (szVal[i] == '-') { sign=-1; ++i; }
03874     else if (szVal[i] == '+')            ++i;
03875     /* Skip digits */
03876     ni = 0;            /* digits in mantissa */
03877     while ((v = szVal[i]) != 0) {
03878         if (!ISDIGIT(v)) break;
03879         ++i;
03880         ++ni;
03881     }
03882     nf  = 0;
03883     ipf = 0;
03884     ipe = 0;
03885     ne  = 0;
03886     if (v) {
03887         /* other than digit nor \0 */
03888         if (szVal[i] == '.') {    /* xxx. */
03889             ++i;
03890             ipf = i;
03891             while ((v = szVal[i]) != 0) {    /* get fraction part. */
03892                 if (!ISDIGIT(v)) break;
03893                 ++i;
03894                 ++nf;
03895             }
03896         }
03897         ipe = 0;        /* Exponent */
03898 
03899         switch (szVal[i]) {
03900         case '\0':
03901             break;
03902         case 'e': case 'E':
03903         case 'd': case 'D':
03904             ++i;
03905             ipe = i;
03906             v = szVal[i];
03907             if ((v == '-') || (v == '+')) ++i;
03908             while ((v=szVal[i]) != 0) {
03909                 if (!ISDIGIT(v)) break;
03910                 ++i;
03911                 ++ne;
03912             }
03913             break;
03914         default:
03915             break;
03916         }
03917     }
03918     nalloc = (ni + nf + BASE_FIG - 1) / BASE_FIG + 1;    /* set effective allocation  */
03919     /* units for szVal[]  */
03920     if (mx <= 0) mx = 1;
03921     nalloc = Max(nalloc, mx);
03922     mx = nalloc;
03923     vp = VpAllocReal(mx);
03924     /* xmalloc() alway returns(or throw interruption) */
03925     vp->MaxPrec = mx;        /* set max precision */
03926     VpSetZero(vp, sign);
03927     VpCtoV(vp, &szVal[ipn], ni, &szVal[ipf], nf, &szVal[ipe], ne);
03928     rb_str_resize(buf, 0);
03929     return vp;
03930 }
03931 
03932 /*
03933  * Assignment(c=a).
03934  * [Input]
03935  *   a   ... RHSV
03936  *   isw ... switch for assignment.
03937  *    c = a  when isw > 0
03938  *    c = -a when isw < 0
03939  *    if c->MaxPrec < a->Prec,then round operation
03940  *    will be performed.
03941  * [Output]
03942  *  c  ... LHSV
03943  */
03944 VP_EXPORT size_t
03945 VpAsgn(Real *c, Real *a, int isw)
03946 {
03947     size_t n;
03948     if(VpIsNaN(a)) {
03949         VpSetNaN(c);
03950         return 0;
03951     }
03952     if(VpIsInf(a)) {
03953         VpSetInf(c,isw*VpGetSign(a));
03954         return 0;
03955     }
03956 
03957     /* check if the RHS is zero */
03958     if(!VpIsZero(a)) {
03959         c->exponent = a->exponent;    /* store  exponent */
03960         VpSetSign(c,(isw*VpGetSign(a)));    /* set sign */
03961         n =(a->Prec < c->MaxPrec) ?(a->Prec) :(c->MaxPrec);
03962         c->Prec = n;
03963         memcpy(c->frac, a->frac, n * sizeof(BDIGIT));
03964         /* Needs round ? */
03965         if(isw!=10) {
03966             /* Not in ActiveRound */
03967             if(c->Prec < a->Prec) {
03968                 VpInternalRound(c,n,(n>0)?a->frac[n-1]:0,a->frac[n]);
03969             } else {
03970                 VpLimitRound(c,0);
03971             }
03972         }
03973     } else {
03974         /* The value of 'a' is zero.  */
03975         VpSetZero(c,isw*VpGetSign(a));
03976         return 1;
03977     }
03978     return c->Prec*BASE_FIG;
03979 }
03980 
03981 /*
03982  *   c = a + b  when operation =  1 or 2
03983  *  = a - b  when operation = -1 or -2.
03984  *   Returns number of significant digits of c
03985  */
03986 VP_EXPORT size_t
03987 VpAddSub(Real *c, Real *a, Real *b, int operation)
03988 {
03989     short sw, isw;
03990     Real *a_ptr, *b_ptr;
03991     size_t n, na, nb, i;
03992     BDIGIT mrv;
03993 
03994 #ifdef BIGDECIMAL_DEBUG
03995     if(gfDebug) {
03996         VPrint(stdout, "VpAddSub(enter) a=% \n", a);
03997         VPrint(stdout, "     b=% \n", b);
03998         printf(" operation=%d\n", operation);
03999     }
04000 #endif /* BIGDECIMAL_DEBUG */
04001 
04002     if(!VpIsDefOP(c,a,b,(operation>0)?1:2)) return 0; /* No significant digits */
04003 
04004     /* check if a or b is zero  */
04005     if(VpIsZero(a)) {
04006         /* a is zero,then assign b to c */
04007         if(!VpIsZero(b)) {
04008             VpAsgn(c, b, operation);
04009         } else {
04010             /* Both a and b are zero. */
04011             if(VpGetSign(a)<0 && operation*VpGetSign(b)<0) {
04012                 /* -0 -0 */
04013                 VpSetZero(c,-1);
04014             } else {
04015                 VpSetZero(c,1);
04016             }
04017             return 1; /* 0: 1 significant digits */
04018         }
04019         return c->Prec*BASE_FIG;
04020     }
04021     if(VpIsZero(b)) {
04022         /* b is zero,then assign a to c. */
04023         VpAsgn(c, a, 1);
04024         return c->Prec*BASE_FIG;
04025     }
04026 
04027     if(operation < 0) sw = -1;
04028     else              sw =  1;
04029 
04030     /* compare absolute value. As a result,|a_ptr|>=|b_ptr| */
04031     if(a->exponent > b->exponent) {
04032         a_ptr = a;
04033         b_ptr = b;
04034     }         /* |a|>|b| */
04035     else if(a->exponent < b->exponent) {
04036         a_ptr = b;
04037         b_ptr = a;
04038     }                /* |a|<|b| */
04039     else {
04040         /* Exponent part of a and b is the same,then compare fraction */
04041         /* part */
04042         na = a->Prec;
04043         nb = b->Prec;
04044         n = Min(na, nb);
04045         for(i=0;i < n; ++i) {
04046             if(a->frac[i] > b->frac[i]) {
04047                 a_ptr = a;
04048                 b_ptr = b;
04049                 goto end_if;
04050             } else if(a->frac[i] < b->frac[i]) {
04051                 a_ptr = b;
04052                 b_ptr = a;
04053                 goto end_if;
04054             }
04055         }
04056         if(na > nb) {
04057          a_ptr = a;
04058             b_ptr = b;
04059             goto end_if;
04060         } else if(na < nb) {
04061             a_ptr = b;
04062             b_ptr = a;
04063             goto end_if;
04064         }
04065         /* |a| == |b| */
04066         if(VpGetSign(a) + sw *VpGetSign(b) == 0) {
04067             VpSetZero(c,1);        /* abs(a)=abs(b) and operation = '-'  */
04068             return c->Prec*BASE_FIG;
04069         }
04070         a_ptr = a;
04071         b_ptr = b;
04072     }
04073 
04074 end_if:
04075     isw = VpGetSign(a) + sw *VpGetSign(b);
04076     /*
04077      *  isw = 0 ...( 1)+(-1),( 1)-( 1),(-1)+(1),(-1)-(-1)
04078      *      = 2 ...( 1)+( 1),( 1)-(-1)
04079      *      =-2 ...(-1)+(-1),(-1)-( 1)
04080      *   If isw==0, then c =(Sign a_ptr)(|a_ptr|-|b_ptr|)
04081      *              else c =(Sign ofisw)(|a_ptr|+|b_ptr|)
04082     */
04083     if(isw) {            /* addition */
04084         VpSetSign(c, 1);
04085         mrv = VpAddAbs(a_ptr, b_ptr, c);
04086         VpSetSign(c, isw / 2);
04087     } else {            /* subtraction */
04088         VpSetSign(c, 1);
04089         mrv = VpSubAbs(a_ptr, b_ptr, c);
04090         if(a_ptr == a) {
04091             VpSetSign(c,VpGetSign(a));
04092         } else    {
04093             VpSetSign(c,VpGetSign(a_ptr) * sw);
04094         }
04095     }
04096     VpInternalRound(c,0,(c->Prec>0)?c->frac[c->Prec-1]:0,mrv);
04097 
04098 #ifdef BIGDECIMAL_DEBUG
04099     if(gfDebug) {
04100         VPrint(stdout, "VpAddSub(result) c=% \n", c);
04101         VPrint(stdout, "     a=% \n", a);
04102         VPrint(stdout, "     b=% \n", b);
04103         printf(" operation=%d\n", operation);
04104     }
04105 #endif /* BIGDECIMAL_DEBUG */
04106     return c->Prec*BASE_FIG;
04107 }
04108 
04109 /*
04110  * Addition of two variable precisional variables
04111  * a and b assuming abs(a)>abs(b).
04112  *   c = abs(a) + abs(b) ; where |a|>=|b|
04113  */
04114 static BDIGIT
04115 VpAddAbs(Real *a, Real *b, Real *c)
04116 {
04117     size_t word_shift;
04118     size_t ap;
04119     size_t bp;
04120     size_t cp;
04121     size_t a_pos;
04122     size_t b_pos, b_pos_with_word_shift;
04123     size_t c_pos;
04124     BDIGIT av, bv, carry, mrv;
04125 
04126 #ifdef BIGDECIMAL_DEBUG
04127     if(gfDebug) {
04128         VPrint(stdout, "VpAddAbs called: a = %\n", a);
04129         VPrint(stdout, "     b = %\n", b);
04130     }
04131 #endif /* BIGDECIMAL_DEBUG */
04132 
04133     word_shift = VpSetPTR(a, b, c, &ap, &bp, &cp, &av, &bv);
04134     a_pos = ap;
04135     b_pos = bp;
04136     c_pos = cp;
04137     if(word_shift==(size_t)-1L) return 0; /* Overflow */
04138     if(b_pos == (size_t)-1L) goto Assign_a;
04139 
04140     mrv = av + bv; /* Most right val. Used for round. */
04141 
04142     /* Just assign the last few digits of b to c because a has no  */
04143     /* corresponding digits to be added. */
04144     while(b_pos + word_shift > a_pos) {
04145         --c_pos;
04146         if(b_pos > 0) {
04147             c->frac[c_pos] = b->frac[--b_pos];
04148         } else {
04149             --word_shift;
04150             c->frac[c_pos] = 0;
04151         }
04152     }
04153 
04154     /* Just assign the last few digits of a to c because b has no */
04155     /* corresponding digits to be added. */
04156     b_pos_with_word_shift = b_pos + word_shift;
04157     while(a_pos > b_pos_with_word_shift) {
04158         c->frac[--c_pos] = a->frac[--a_pos];
04159     }
04160     carry = 0;    /* set first carry be zero */
04161 
04162     /* Now perform addition until every digits of b will be */
04163     /* exhausted. */
04164     while(b_pos > 0) {
04165         c->frac[--c_pos] = a->frac[--a_pos] + b->frac[--b_pos] + carry;
04166         if(c->frac[c_pos] >= BASE) {
04167             c->frac[c_pos] -= BASE;
04168             carry = 1;
04169         } else {
04170             carry = 0;
04171         }
04172     }
04173 
04174     /* Just assign the first few digits of a with considering */
04175     /* the carry obtained so far because b has been exhausted. */
04176     while(a_pos > 0) {
04177         c->frac[--c_pos] = a->frac[--a_pos] + carry;
04178         if(c->frac[c_pos] >= BASE) {
04179             c->frac[c_pos] -= BASE;
04180             carry = 1;
04181         } else {
04182             carry = 0;
04183         }
04184     }
04185     if(c_pos) c->frac[c_pos - 1] += carry;
04186     goto Exit;
04187 
04188 Assign_a:
04189     VpAsgn(c, a, 1);
04190     mrv = 0;
04191 
04192 Exit:
04193 
04194 #ifdef BIGDECIMAL_DEBUG
04195     if(gfDebug) {
04196         VPrint(stdout, "VpAddAbs exit: c=% \n", c);
04197     }
04198 #endif /* BIGDECIMAL_DEBUG */
04199     return mrv;
04200 }
04201 
04202 /*
04203  * c = abs(a) - abs(b)
04204  */
04205 static BDIGIT
04206 VpSubAbs(Real *a, Real *b, Real *c)
04207 {
04208     size_t word_shift;
04209     size_t ap;
04210     size_t bp;
04211     size_t cp;
04212     size_t a_pos;
04213     size_t b_pos, b_pos_with_word_shift;
04214     size_t c_pos;
04215     BDIGIT av, bv, borrow, mrv;
04216 
04217 #ifdef BIGDECIMAL_DEBUG
04218     if(gfDebug) {
04219         VPrint(stdout, "VpSubAbs called: a = %\n", a);
04220         VPrint(stdout, "     b = %\n", b);
04221     }
04222 #endif /* BIGDECIMAL_DEBUG */
04223 
04224     word_shift = VpSetPTR(a, b, c, &ap, &bp, &cp, &av, &bv);
04225     a_pos = ap;
04226     b_pos = bp;
04227     c_pos = cp;
04228     if(word_shift==(size_t)-1L) return 0; /* Overflow */
04229     if(b_pos == (size_t)-1L) goto Assign_a;
04230 
04231     if(av >= bv) {
04232         mrv = av - bv;
04233         borrow = 0;
04234     } else {
04235         mrv    = 0;
04236         borrow = 1;
04237     }
04238 
04239     /* Just assign the values which are the BASE subtracted by   */
04240     /* each of the last few digits of the b because the a has no */
04241     /* corresponding digits to be subtracted. */
04242     if(b_pos + word_shift > a_pos) {
04243         while(b_pos + word_shift > a_pos) {
04244             --c_pos;
04245             if(b_pos > 0) {
04246                 c->frac[c_pos] = BASE - b->frac[--b_pos] - borrow;
04247             } else {
04248                 --word_shift;
04249                 c->frac[c_pos] = BASE - borrow;
04250             }
04251             borrow = 1;
04252         }
04253     }
04254     /* Just assign the last few digits of a to c because b has no */
04255     /* corresponding digits to subtract. */
04256 
04257     b_pos_with_word_shift = b_pos + word_shift;
04258     while(a_pos > b_pos_with_word_shift) {
04259         c->frac[--c_pos] = a->frac[--a_pos];
04260     }
04261 
04262     /* Now perform subtraction until every digits of b will be */
04263     /* exhausted. */
04264     while(b_pos > 0) {
04265         --c_pos;
04266         if(a->frac[--a_pos] < b->frac[--b_pos] + borrow) {
04267             c->frac[c_pos] = BASE + a->frac[a_pos] - b->frac[b_pos] - borrow;
04268             borrow = 1;
04269         } else {
04270             c->frac[c_pos] = a->frac[a_pos] - b->frac[b_pos] - borrow;
04271             borrow = 0;
04272         }
04273     }
04274 
04275     /* Just assign the first few digits of a with considering */
04276     /* the borrow obtained so far because b has been exhausted. */
04277     while(a_pos > 0) {
04278         --c_pos;
04279         if(a->frac[--a_pos] < borrow) {
04280             c->frac[c_pos] = BASE + a->frac[a_pos] - borrow;
04281             borrow = 1;
04282         } else {
04283             c->frac[c_pos] = a->frac[a_pos] - borrow;
04284             borrow = 0;
04285         }
04286     }
04287     if(c_pos) c->frac[c_pos - 1] -= borrow;
04288     goto Exit;
04289 
04290 Assign_a:
04291     VpAsgn(c, a, 1);
04292     mrv = 0;
04293 
04294 Exit:
04295 #ifdef BIGDECIMAL_DEBUG
04296     if(gfDebug) {
04297         VPrint(stdout, "VpSubAbs exit: c=% \n", c);
04298     }
04299 #endif /* BIGDECIMAL_DEBUG */
04300     return mrv;
04301 }
04302 
04303 /*
04304  * Note: If(av+bv)>= HALF_BASE,then 1 will be added to the least significant
04305  *    digit of c(In case of addition).
04306  * ------------------------- figure of output -----------------------------------
04307  *      a =  xxxxxxxxxxx
04308  *      b =    xxxxxxxxxx
04309  *      c =xxxxxxxxxxxxxxx
04310  *      word_shift =  |   |
04311  *      right_word =  |    | (Total digits in RHSV)
04312  *      left_word  = |   |   (Total digits in LHSV)
04313  *      a_pos      =    |
04314  *      b_pos      =     |
04315  *      c_pos      =      |
04316  */
04317 static size_t
04318 VpSetPTR(Real *a, Real *b, Real *c, size_t *a_pos, size_t *b_pos, size_t *c_pos, BDIGIT *av, BDIGIT *bv)
04319 {
04320     size_t left_word, right_word, word_shift;
04321     c->frac[0] = 0;
04322     *av = *bv = 0;
04323     word_shift =((a->exponent) -(b->exponent));
04324     left_word = b->Prec + word_shift;
04325     right_word = Max((a->Prec),left_word);
04326     left_word =(c->MaxPrec) - 1;    /* -1 ... prepare for round up */
04327     /*
04328      * check if 'round' is needed.
04329      */
04330     if(right_word > left_word) {    /* round ? */
04331         /*---------------------------------
04332          *  Actual size of a = xxxxxxAxx
04333          *  Actual size of b = xxxBxxxxx
04334          *  Max. size of   c = xxxxxx
04335          *  Round off        =   |-----|
04336          *  c_pos            =   |
04337          *  right_word       =   |
04338          *  a_pos            =    |
04339          */
04340         *c_pos = right_word = left_word + 1;    /* Set resulting precision */
04341         /* be equal to that of c */
04342         if((a->Prec) >=(c->MaxPrec)) {
04343             /*
04344              *   a =  xxxxxxAxxx
04345              *   c =  xxxxxx
04346              *   a_pos =    |
04347              */
04348             *a_pos = left_word;
04349             *av = a->frac[*a_pos];    /* av is 'A' shown in above. */
04350         } else {
04351             /*
04352              *   a = xxxxxxx
04353              *   c = xxxxxxxxxx
04354              *  a_pos =     |
04355              */
04356             *a_pos = a->Prec;
04357         }
04358         if((b->Prec + word_shift) >= c->MaxPrec) {
04359             /*
04360              *   a = xxxxxxxxx
04361              *   b =  xxxxxxxBxxx
04362              *   c = xxxxxxxxxxx
04363              *  b_pos =   |
04364              */
04365             if(c->MaxPrec >=(word_shift + 1)) {
04366                 *b_pos = c->MaxPrec - word_shift - 1;
04367                 *bv = b->frac[*b_pos];
04368             } else {
04369                 *b_pos = -1L;
04370             }
04371         } else {
04372             /*
04373              *   a = xxxxxxxxxxxxxxxx
04374              *   b =  xxxxxx
04375              *   c = xxxxxxxxxxxxx
04376              *  b_pos =     |
04377              */
04378             *b_pos = b->Prec;
04379         }
04380     } else {            /* The MaxPrec of c - 1 > The Prec of a + b  */
04381         /*
04382          *    a =   xxxxxxx
04383          *    b =   xxxxxx
04384          *    c = xxxxxxxxxxx
04385          *   c_pos =   |
04386          */
04387         *b_pos = b->Prec;
04388         *a_pos = a->Prec;
04389         *c_pos = right_word + 1;
04390     }
04391     c->Prec = *c_pos;
04392     c->exponent = a->exponent;
04393     if(!AddExponent(c,1)) return (size_t)-1L;
04394     return word_shift;
04395 }
04396 
04397 /*
04398  * Return number og significant digits
04399  *       c = a * b , Where a = a0a1a2 ... an
04400  *             b = b0b1b2 ... bm
04401  *             c = c0c1c2 ... cl
04402  *          a0 a1 ... an   * bm
04403  *       a0 a1 ... an   * bm-1
04404  *         .   .    .
04405  *       .   .   .
04406  *        a0 a1 .... an    * b0
04407  *      +_____________________________
04408  *     c0 c1 c2  ......  cl
04409  *     nc      <---|
04410  *     MaxAB |--------------------|
04411  */
04412 VP_EXPORT size_t
04413 VpMult(Real *c, Real *a, Real *b)
04414 {
04415     size_t MxIndA, MxIndB, MxIndAB, MxIndC;
04416     size_t ind_c, i, ii, nc;
04417     size_t ind_as, ind_ae, ind_bs;
04418     BDIGIT carry;
04419     BDIGIT_DBL s;
04420     Real *w;
04421 
04422 #ifdef BIGDECIMAL_DEBUG
04423     if(gfDebug) {
04424         VPrint(stdout, "VpMult(Enter): a=% \n", a);
04425         VPrint(stdout, "      b=% \n", b);
04426     }
04427 #endif /* BIGDECIMAL_DEBUG */
04428 
04429     if(!VpIsDefOP(c,a,b,3)) return 0; /* No significant digit */
04430 
04431     if(VpIsZero(a) || VpIsZero(b)) {
04432         /* at least a or b is zero */
04433         VpSetZero(c,VpGetSign(a)*VpGetSign(b));
04434         return 1; /* 0: 1 significant digit */
04435     }
04436 
04437     if(VpIsOne(a)) {
04438         VpAsgn(c, b, VpGetSign(a));
04439         goto Exit;
04440     }
04441     if(VpIsOne(b)) {
04442         VpAsgn(c, a, VpGetSign(b));
04443         goto Exit;
04444     }
04445     if((b->Prec) >(a->Prec)) {
04446         /* Adjust so that digits(a)>digits(b) */
04447         w = a;
04448         a = b;
04449         b = w;
04450     }
04451     w = NULL;
04452     MxIndA = a->Prec - 1;
04453     MxIndB = b->Prec - 1;
04454     MxIndC = c->MaxPrec - 1;
04455     MxIndAB = a->Prec + b->Prec - 1;
04456 
04457     if(MxIndC < MxIndAB) {    /* The Max. prec. of c < Prec(a)+Prec(b) */
04458         w = c;
04459         c = VpAlloc((size_t)((MxIndAB + 1) * BASE_FIG), "#0");
04460         MxIndC = MxIndAB;
04461     }
04462 
04463     /* set LHSV c info */
04464 
04465     c->exponent = a->exponent;    /* set exponent */
04466     if(!AddExponent(c,b->exponent)) {
04467         if(w) VpFree(c);
04468         return 0;
04469     }
04470     VpSetSign(c,VpGetSign(a)*VpGetSign(b));    /* set sign  */
04471     carry = 0;
04472     nc = ind_c = MxIndAB;
04473     memset(c->frac, 0, (nc + 1) * sizeof(BDIGIT));        /* Initialize c  */
04474     c->Prec = nc + 1;        /* set precision */
04475     for(nc = 0; nc < MxIndAB; ++nc, --ind_c) {
04476         if(nc < MxIndB) {    /* The left triangle of the Fig. */
04477             ind_as = MxIndA - nc;
04478             ind_ae = MxIndA;
04479             ind_bs = MxIndB;
04480         } else if(nc <= MxIndA) {    /* The middle rectangular of the Fig. */
04481             ind_as = MxIndA - nc;
04482             ind_ae = MxIndA -(nc - MxIndB);
04483             ind_bs = MxIndB;
04484         } else if(nc > MxIndA) {    /*  The right triangle of the Fig. */
04485             ind_as = 0;
04486             ind_ae = MxIndAB - nc - 1;
04487             ind_bs = MxIndB -(nc - MxIndA);
04488         }
04489 
04490         for(i = ind_as; i <= ind_ae; ++i) {
04491             s = (BDIGIT_DBL)a->frac[i] * b->frac[ind_bs--];
04492             carry = (BDIGIT)(s / BASE);
04493             s -= (BDIGIT_DBL)carry * BASE;
04494             c->frac[ind_c] += (BDIGIT)s;
04495             if(c->frac[ind_c] >= BASE) {
04496                 s = c->frac[ind_c] / BASE;
04497                 carry += (BDIGIT)s;
04498                 c->frac[ind_c] -= (BDIGIT)(s * BASE);
04499             }
04500             if(carry) {
04501                 ii = ind_c;
04502                 while(ii-- > 0) {
04503                     c->frac[ii] += carry;
04504                     if(c->frac[ii] >= BASE) {
04505                         carry = c->frac[ii] / BASE;
04506                         c->frac[ii] -= (carry * BASE);
04507                     } else {
04508                         break;
04509                     }
04510                 }
04511             }
04512         }
04513     }
04514     if(w != NULL) {        /* free work variable */
04515         VpNmlz(c);
04516         VpAsgn(w, c, 1);
04517         VpFree(c);
04518         c = w;
04519     } else {
04520         VpLimitRound(c,0);
04521     }
04522 
04523 Exit:
04524 #ifdef BIGDECIMAL_DEBUG
04525     if(gfDebug) {
04526         VPrint(stdout, "VpMult(c=a*b): c=% \n", c);
04527         VPrint(stdout, "      a=% \n", a);
04528         VPrint(stdout, "      b=% \n", b);
04529     }
04530 #endif /*BIGDECIMAL_DEBUG */
04531     return c->Prec*BASE_FIG;
04532 }
04533 
04534 /*
04535  *   c = a / b,  remainder = r
04536  */
04537 VP_EXPORT size_t
04538 VpDivd(Real *c, Real *r, Real *a, Real *b)
04539 {
04540     size_t word_a, word_b, word_c, word_r;
04541     size_t i, n, ind_a, ind_b, ind_c, ind_r;
04542     size_t nLoop;
04543     BDIGIT_DBL q, b1, b1p1, b1b2, b1b2p1, r1r2;
04544     BDIGIT borrow, borrow1, borrow2;
04545     BDIGIT_DBL qb;
04546 
04547 #ifdef BIGDECIMAL_DEBUG
04548     if(gfDebug) {
04549         VPrint(stdout, " VpDivd(c=a/b)  a=% \n", a);
04550         VPrint(stdout, "    b=% \n", b);
04551     }
04552 #endif /*BIGDECIMAL_DEBUG */
04553 
04554     VpSetNaN(r);
04555     if(!VpIsDefOP(c,a,b,4)) goto Exit;
04556     if(VpIsZero(a)&&VpIsZero(b)) {
04557         VpSetNaN(c);
04558         return VpException(VP_EXCEPTION_NaN,"(VpDivd) 0/0 not defined(NaN)",0);
04559     }
04560     if(VpIsZero(b)) {
04561         VpSetInf(c,VpGetSign(a)*VpGetSign(b));
04562         return VpException(VP_EXCEPTION_ZERODIVIDE,"(VpDivd) Divide by zero",0);
04563     }
04564     if(VpIsZero(a)) {
04565         /* numerator a is zero  */
04566         VpSetZero(c,VpGetSign(a)*VpGetSign(b));
04567         VpSetZero(r,VpGetSign(a)*VpGetSign(b));
04568         goto Exit;
04569     }
04570     if(VpIsOne(b)) {
04571         /* divide by one  */
04572         VpAsgn(c, a, VpGetSign(b));
04573         VpSetZero(r,VpGetSign(a));
04574         goto Exit;
04575     }
04576 
04577     word_a = a->Prec;
04578     word_b = b->Prec;
04579     word_c = c->MaxPrec;
04580     word_r = r->MaxPrec;
04581 
04582     ind_c = 0;
04583     ind_r = 1;
04584 
04585     if(word_a >= word_r) goto space_error;
04586 
04587     r->frac[0] = 0;
04588     while(ind_r <= word_a) {
04589         r->frac[ind_r] = a->frac[ind_r - 1];
04590         ++ind_r;
04591     }
04592 
04593     while(ind_r < word_r) r->frac[ind_r++] = 0;
04594     while(ind_c < word_c) c->frac[ind_c++] = 0;
04595 
04596     /* initial procedure */
04597     b1 = b1p1 = b->frac[0];
04598     if(b->Prec <= 1) {
04599         b1b2p1 = b1b2 = b1p1 * BASE;
04600     } else {
04601         b1p1 = b1 + 1;
04602         b1b2p1 = b1b2 = b1 * BASE + b->frac[1];
04603         if(b->Prec > 2) ++b1b2p1;
04604     }
04605 
04606     /* */
04607     /* loop start */
04608     ind_c = word_r - 1;
04609     nLoop = Min(word_c,ind_c);
04610     ind_c = 1;
04611     while(ind_c < nLoop) {
04612         if(r->frac[ind_c] == 0) {
04613             ++ind_c;
04614             continue;
04615         }
04616         r1r2 = (BDIGIT_DBL)r->frac[ind_c] * BASE + r->frac[ind_c + 1];
04617         if(r1r2 == b1b2) {
04618             /* The first two word digits is the same */
04619             ind_b = 2;
04620             ind_a = ind_c + 2;
04621             while(ind_b < word_b) {
04622                 if(r->frac[ind_a] < b->frac[ind_b]) goto div_b1p1;
04623                 if(r->frac[ind_a] > b->frac[ind_b]) break;
04624                 ++ind_a;
04625                 ++ind_b;
04626             }
04627             /* The first few word digits of r and b is the same and */
04628             /* the first different word digit of w is greater than that */
04629             /* of b, so quotinet is 1 and just subtract b from r. */
04630             borrow = 0;        /* quotient=1, then just r-b */
04631             ind_b = b->Prec - 1;
04632             ind_r = ind_c + ind_b;
04633             if(ind_r >= word_r) goto space_error;
04634             n = ind_b;
04635             for(i = 0; i <= n; ++i) {
04636                 if(r->frac[ind_r] < b->frac[ind_b] + borrow) {
04637                     r->frac[ind_r] += (BASE - (b->frac[ind_b] + borrow));
04638                     borrow = 1;
04639                 } else {
04640                     r->frac[ind_r] = r->frac[ind_r] - b->frac[ind_b] - borrow;
04641                     borrow = 0;
04642                 }
04643                 --ind_r;
04644                 --ind_b;
04645             }
04646             ++c->frac[ind_c];
04647             goto carry;
04648         }
04649         /* The first two word digits is not the same, */
04650         /* then compare magnitude, and divide actually. */
04651         if(r1r2 >= b1b2p1) {
04652             q = r1r2 / b1b2p1;  /* q == (BDIGIT)q  */
04653             c->frac[ind_c] += (BDIGIT)q;
04654             ind_r = b->Prec + ind_c - 1;
04655             goto sub_mult;
04656         }
04657 
04658 div_b1p1:
04659         if(ind_c + 1 >= word_c) goto out_side;
04660         q = r1r2 / b1p1;  /* q == (BDIGIT)q */
04661         c->frac[ind_c + 1] += (BDIGIT)q;
04662         ind_r = b->Prec + ind_c;
04663 
04664 sub_mult:
04665         borrow1 = borrow2 = 0;
04666         ind_b = word_b - 1;
04667         if(ind_r >= word_r) goto space_error;
04668         n = ind_b;
04669         for(i = 0; i <= n; ++i) {
04670             /* now, perform r = r - q * b */
04671             qb = q * b->frac[ind_b];
04672             if (qb < BASE) borrow1 = 0;
04673             else {
04674                 borrow1 = (BDIGIT)(qb / BASE);
04675                 qb -= (BDIGIT_DBL)borrow1 * BASE;       /* get qb < BASE */
04676             }
04677             if(r->frac[ind_r] < qb) {
04678                 r->frac[ind_r] += (BDIGIT)(BASE - qb);
04679                 borrow2 = borrow2 + borrow1 + 1;
04680             } else {
04681                 r->frac[ind_r] -= (BDIGIT)qb;
04682                 borrow2 += borrow1;
04683             }
04684             if(borrow2) {
04685                 if(r->frac[ind_r - 1] < borrow2) {
04686                     r->frac[ind_r - 1] += (BASE - borrow2);
04687                     borrow2 = 1;
04688                 } else {
04689                     r->frac[ind_r - 1] -= borrow2;
04690                     borrow2 = 0;
04691                 }
04692             }
04693             --ind_r;
04694             --ind_b;
04695         }
04696 
04697         r->frac[ind_r] -= borrow2;
04698 carry:
04699         ind_r = ind_c;
04700         while(c->frac[ind_r] >= BASE) {
04701             c->frac[ind_r] -= BASE;
04702             --ind_r;
04703             ++c->frac[ind_r];
04704         }
04705     }
04706     /* End of operation, now final arrangement */
04707 out_side:
04708     c->Prec = word_c;
04709     c->exponent = a->exponent;
04710     if(!AddExponent(c,2))   return 0;
04711     if(!AddExponent(c,-(b->exponent))) return 0;
04712 
04713     VpSetSign(c,VpGetSign(a)*VpGetSign(b));
04714     VpNmlz(c);            /* normalize c */
04715     r->Prec = word_r;
04716     r->exponent = a->exponent;
04717     if(!AddExponent(r,1)) return 0;
04718     VpSetSign(r,VpGetSign(a));
04719     VpNmlz(r);            /* normalize r(remainder) */
04720     goto Exit;
04721 
04722 space_error:
04723 #ifdef BIGDECIMAL_DEBUG
04724     if(gfDebug) {
04725         printf("   word_a=%lu\n", word_a);
04726         printf("   word_b=%lu\n", word_b);
04727         printf("   word_c=%lu\n", word_c);
04728         printf("   word_r=%lu\n", word_r);
04729         printf("   ind_r =%lu\n", ind_r);
04730     }
04731 #endif /* BIGDECIMAL_DEBUG */
04732     rb_bug("ERROR(VpDivd): space for remainder too small.");
04733 
04734 Exit:
04735 #ifdef BIGDECIMAL_DEBUG
04736     if(gfDebug) {
04737         VPrint(stdout, " VpDivd(c=a/b), c=% \n", c);
04738         VPrint(stdout, "    r=% \n", r);
04739     }
04740 #endif /* BIGDECIMAL_DEBUG */
04741     return c->Prec*BASE_FIG;
04742 }
04743 
04744 /*
04745  *  Input  a = 00000xxxxxxxx En(5 preceeding zeros)
04746  *  Output a = xxxxxxxx En-5
04747  */
04748 static int
04749 VpNmlz(Real *a)
04750 {
04751     size_t ind_a, i;
04752 
04753     if (!VpIsDef(a)) goto NoVal;
04754     if (VpIsZero(a)) goto NoVal;
04755 
04756     ind_a = a->Prec;
04757     while (ind_a--) {
04758         if (a->frac[ind_a]) {
04759             a->Prec = ind_a + 1;
04760             i = 0;
04761             while (a->frac[i] == 0) ++i;        /* skip the first few zeros */
04762             if (i) {
04763                 a->Prec -= i;
04764                 if (!AddExponent(a, -(SIGNED_VALUE)i)) return 0;
04765                 memmove(&a->frac[0], &a->frac[i], a->Prec*sizeof(BDIGIT));
04766             }
04767             return 1;
04768         }
04769     }
04770     /* a is zero(no non-zero digit) */
04771     VpSetZero(a, VpGetSign(a));
04772     return 0;
04773 
04774 NoVal:
04775     a->frac[0] = 0;
04776     a->Prec = 1;
04777     return 0;
04778 }
04779 
04780 /*
04781  *  VpComp = 0  ... if a=b,
04782  *   Pos  ... a>b,
04783  *   Neg  ... a<b.
04784  *   999  ... result undefined(NaN)
04785  */
04786 VP_EXPORT int
04787 VpComp(Real *a, Real *b)
04788 {
04789     int val;
04790     size_t mx, ind;
04791     int e;
04792     val = 0;
04793     if(VpIsNaN(a)||VpIsNaN(b)) return 999;
04794     if(!VpIsDef(a)) {
04795         if(!VpIsDef(b)) e = a->sign - b->sign;
04796         else             e = a->sign;
04797         if(e>0)   return  1;
04798         else if(e<0) return -1;
04799         else   return  0;
04800     }
04801     if(!VpIsDef(b)) {
04802         e = -b->sign;
04803         if(e>0) return  1;
04804         else return -1;
04805     }
04806     /* Zero check */
04807     if(VpIsZero(a)) {
04808         if(VpIsZero(b))      return 0; /* both zero */
04809         val = -VpGetSign(b);
04810         goto Exit;
04811     }
04812     if(VpIsZero(b)) {
04813         val = VpGetSign(a);
04814         goto Exit;
04815     }
04816 
04817     /* compare sign */
04818     if(VpGetSign(a) > VpGetSign(b)) {
04819         val = 1;        /* a>b */
04820         goto Exit;
04821     }
04822     if(VpGetSign(a) < VpGetSign(b)) {
04823         val = -1;        /* a<b */
04824         goto Exit;
04825     }
04826 
04827     /* a and b have same sign, && signe!=0,then compare exponent */
04828     if((a->exponent) >(b->exponent)) {
04829         val = VpGetSign(a);
04830         goto Exit;
04831     }
04832     if((a->exponent) <(b->exponent)) {
04833         val = -VpGetSign(b);
04834         goto Exit;
04835     }
04836 
04837     /* a and b have same exponent, then compare significand. */
04838     mx =((a->Prec) <(b->Prec)) ?(a->Prec) :(b->Prec);
04839     ind = 0;
04840     while(ind < mx) {
04841         if((a->frac[ind]) >(b->frac[ind])) {
04842             val = VpGetSign(a);
04843          goto Exit;
04844         }
04845         if((a->frac[ind]) <(b->frac[ind])) {
04846             val = -VpGetSign(b);
04847             goto Exit;
04848         }
04849         ++ind;
04850     }
04851     if((a->Prec) >(b->Prec)) {
04852         val = VpGetSign(a);
04853     } else if((a->Prec) <(b->Prec)) {
04854         val = -VpGetSign(b);
04855     }
04856 
04857 Exit:
04858     if  (val> 1) val =  1;
04859     else if(val<-1) val = -1;
04860 
04861 #ifdef BIGDECIMAL_DEBUG
04862     if(gfDebug) {
04863         VPrint(stdout, " VpComp a=%\n", a);
04864         VPrint(stdout, "  b=%\n", b);
04865         printf("  ans=%d\n", val);
04866     }
04867 #endif /* BIGDECIMAL_DEBUG */
04868     return (int)val;
04869 }
04870 
04871 #ifdef BIGDECIMAL_ENABLE_VPRINT
04872 /*
04873  *    cntl_chr ... ASCIIZ Character, print control characters
04874  *     Available control codes:
04875  *      %  ... VP variable. To print '%', use '%%'.
04876  *      \n ... new line
04877  *      \b ... backspace
04878  *           ... tab
04879  *     Note: % must must not appear more than once
04880  *    a  ... VP variable to be printed
04881  */
04882 VP_EXPORT int
04883 VPrint(FILE *fp, const char *cntl_chr, Real *a)
04884 {
04885     size_t i, j, nc, nd, ZeroSup;
04886     BDIGIT m, e, nn;
04887 
04888     /* Check if NaN & Inf. */
04889     if(VpIsNaN(a)) {
04890         fprintf(fp,SZ_NaN);
04891         return 8;
04892     }
04893     if(VpIsPosInf(a)) {
04894         fprintf(fp,SZ_INF);
04895         return 8;
04896     }
04897     if(VpIsNegInf(a)) {
04898         fprintf(fp,SZ_NINF);
04899         return 9;
04900     }
04901     if(VpIsZero(a)) {
04902         fprintf(fp,"0.0");
04903         return 3;
04904     }
04905 
04906     j = 0;
04907     nd = nc = 0;        /*  nd : number of digits in fraction part(every 10 digits, */
04908     /*    nd<=10). */
04909     /*  nc : number of caracters printed  */
04910     ZeroSup = 1;        /* Flag not to print the leading zeros as 0.00xxxxEnn */
04911     while(*(cntl_chr + j)) {
04912         if((*(cntl_chr + j) == '%') &&(*(cntl_chr + j + 1) != '%')) {
04913          nc = 0;
04914          if(!VpIsZero(a)) {
04915                 if(VpGetSign(a) < 0) {
04916                     fprintf(fp, "-");
04917                     ++nc;
04918                 }
04919                 nc += fprintf(fp, "0.");
04920                 for(i=0; i < a->Prec; ++i) {
04921                     m = BASE1;
04922                     e = a->frac[i];
04923                     while(m) {
04924                         nn = e / m;
04925                         if((!ZeroSup) || nn) {
04926                             nc += fprintf(fp, "%lu", (unsigned long)nn);    /* The leading zero(s) */
04927                             /* as 0.00xx will not */
04928                             /* be printed. */
04929                             ++nd;
04930                             ZeroSup = 0;    /* Set to print succeeding zeros */
04931                         }
04932                         if(nd >= 10) {    /* print ' ' after every 10 digits */
04933                             nd = 0;
04934                             nc += fprintf(fp, " ");
04935                         }
04936                         e = e - nn * m;
04937                         m /= 10;
04938                     }
04939                 }
04940                 nc += fprintf(fp, "E%"PRIdSIZE, VpExponent10(a));
04941             } else {
04942                 nc += fprintf(fp, "0.0");
04943             }
04944         } else {
04945             ++nc;
04946             if(*(cntl_chr + j) == '\\') {
04947                 switch(*(cntl_chr + j + 1)) {
04948                 case 'n':
04949                     fprintf(fp, "\n");
04950                     ++j;
04951                     break;
04952                 case 't':
04953                     fprintf(fp, "\t");
04954                     ++j;
04955                  break;
04956                 case 'b':
04957                     fprintf(fp, "\n");
04958                     ++j;
04959                     break;
04960                 default:
04961                     fprintf(fp, "%c", *(cntl_chr + j));
04962                     break;
04963                 }
04964             } else {
04965                 fprintf(fp, "%c", *(cntl_chr + j));
04966                 if(*(cntl_chr + j) == '%') ++j;
04967             }
04968         }
04969         j++;
04970     }
04971     return (int)nc;
04972 }
04973 #endif /* BIGDECIMAL_ENABLE_VPRINT */
04974 
04975 static void
04976 VpFormatSt(char *psz, size_t fFmt)
04977 {
04978     size_t ie, i, nf = 0;
04979     char ch;
04980 
04981     if(fFmt<=0) return;
04982 
04983     ie = strlen(psz);
04984     for(i = 0; i < ie; ++i) {
04985         ch = psz[i];
04986         if(!ch) break;
04987         if(ISSPACE(ch) || ch=='-' || ch=='+') continue;
04988         if(ch == '.')                { nf = 0;continue;}
04989         if(ch == 'E') break;
04990         nf++;
04991         if(nf > fFmt) {
04992             memmove(psz + i + 1, psz + i, ie - i + 1);
04993             ++ie;
04994             nf = 0;
04995             psz[i] = ' ';
04996         }
04997     }
04998 }
04999 
05000 VP_EXPORT ssize_t
05001 VpExponent10(Real *a)
05002 {
05003     ssize_t ex;
05004     size_t n;
05005 
05006     if (!VpHasVal(a)) return 0;
05007 
05008     ex = a->exponent * (ssize_t)BASE_FIG;
05009     n = BASE1;
05010     while ((a->frac[0] / n) == 0) {
05011          --ex;
05012          n /= 10;
05013     }
05014     return ex;
05015 }
05016 
05017 VP_EXPORT void
05018 VpSzMantissa(Real *a,char *psz)
05019 {
05020     size_t i, n, ZeroSup;
05021     BDIGIT_DBL m, e, nn;
05022 
05023     if(VpIsNaN(a)) {
05024         sprintf(psz,SZ_NaN);
05025         return;
05026     }
05027     if(VpIsPosInf(a)) {
05028         sprintf(psz,SZ_INF);
05029         return;
05030     }
05031     if(VpIsNegInf(a)) {
05032         sprintf(psz,SZ_NINF);
05033         return;
05034     }
05035 
05036     ZeroSup = 1;        /* Flag not to print the leading zeros as 0.00xxxxEnn */
05037     if(!VpIsZero(a)) {
05038         if(VpGetSign(a) < 0) *psz++ = '-';
05039         n = a->Prec;
05040         for (i=0; i < n; ++i) {
05041             m = BASE1;
05042             e = a->frac[i];
05043             while (m) {
05044                 nn = e / m;
05045                 if((!ZeroSup) || nn) {
05046                     sprintf(psz, "%lu", (unsigned long)nn);    /* The leading zero(s) */
05047                     psz += strlen(psz);
05048                     /* as 0.00xx will be ignored. */
05049                     ZeroSup = 0;    /* Set to print succeeding zeros */
05050                 }
05051                 e = e - nn * m;
05052                 m /= 10;
05053             }
05054         }
05055         *psz = 0;
05056         while(psz[-1]=='0') *(--psz) = 0;
05057     } else {
05058         if(VpIsPosZero(a)) sprintf(psz, "0");
05059         else      sprintf(psz, "-0");
05060     }
05061 }
05062 
05063 VP_EXPORT int
05064 VpToSpecialString(Real *a,char *psz,int fPlus)
05065 /* fPlus =0:default, =1: set ' ' before digits , =2: set '+' before digits. */
05066 {
05067     if(VpIsNaN(a)) {
05068         sprintf(psz,SZ_NaN);
05069         return 1;
05070     }
05071 
05072     if(VpIsPosInf(a)) {
05073         if(fPlus==1) {
05074            *psz++ = ' ';
05075         } else if(fPlus==2) {
05076            *psz++ = '+';
05077         }
05078         sprintf(psz,SZ_INF);
05079         return 1;
05080     }
05081     if(VpIsNegInf(a)) {
05082         sprintf(psz,SZ_NINF);
05083         return 1;
05084     }
05085     if(VpIsZero(a)) {
05086         if(VpIsPosZero(a)) {
05087             if(fPlus==1)      sprintf(psz, " 0.0");
05088             else if(fPlus==2) sprintf(psz, "+0.0");
05089             else              sprintf(psz, "0.0");
05090         } else    sprintf(psz, "-0.0");
05091         return 1;
05092     }
05093     return 0;
05094 }
05095 
05096 VP_EXPORT void
05097 VpToString(Real *a, char *psz, size_t fFmt, int fPlus)
05098 /* fPlus =0:default, =1: set ' ' before digits , =2:set '+' before digits. */
05099 {
05100     size_t i, n, ZeroSup;
05101     BDIGIT shift, m, e, nn;
05102     char *pszSav = psz;
05103     ssize_t ex;
05104 
05105     if (VpToSpecialString(a, psz, fPlus)) return;
05106 
05107     ZeroSup = 1;    /* Flag not to print the leading zeros as 0.00xxxxEnn */
05108 
05109     if (VpGetSign(a) < 0) *psz++ = '-';
05110     else if (fPlus == 1)  *psz++ = ' ';
05111     else if (fPlus == 2)  *psz++ = '+';
05112 
05113     *psz++ = '0';
05114     *psz++ = '.';
05115     n = a->Prec;
05116     for(i=0;i < n;++i) {
05117         m = BASE1;
05118         e = a->frac[i];
05119         while(m) {
05120             nn = e / m;
05121             if((!ZeroSup) || nn) {
05122                 sprintf(psz, "%lu", (unsigned long)nn);    /* The reading zero(s) */
05123                 psz += strlen(psz);
05124                 /* as 0.00xx will be ignored. */
05125                 ZeroSup = 0;    /* Set to print succeeding zeros */
05126             }
05127             e = e - nn * m;
05128             m /= 10;
05129         }
05130     }
05131     ex = a->exponent * (ssize_t)BASE_FIG;
05132     shift = BASE1;
05133     while(a->frac[0] / shift == 0) {
05134         --ex;
05135         shift /= 10;
05136     }
05137     while(psz[-1]=='0') *(--psz) = 0;
05138     sprintf(psz, "E%"PRIdSIZE, ex);
05139     if(fFmt) VpFormatSt(pszSav, fFmt);
05140 }
05141 
05142 VP_EXPORT void
05143 VpToFString(Real *a, char *psz, size_t fFmt, int fPlus)
05144 /* fPlus =0:default,=1: set ' ' before digits ,set '+' before digits. */
05145 {
05146     size_t i, n;
05147     BDIGIT m, e, nn;
05148     char *pszSav = psz;
05149     ssize_t ex;
05150 
05151     if(VpToSpecialString(a,psz,fPlus)) return;
05152 
05153     if(VpGetSign(a) < 0) *psz++ = '-';
05154     else if(fPlus==1)    *psz++ = ' ';
05155     else if(fPlus==2)    *psz++ = '+';
05156 
05157     n  = a->Prec;
05158     ex = a->exponent;
05159     if(ex<=0) {
05160        *psz++ = '0';*psz++ = '.';
05161        while(ex<0) {
05162           for(i=0;i<BASE_FIG;++i) *psz++ = '0';
05163           ++ex;
05164        }
05165        ex = -1;
05166     }
05167 
05168     for(i=0;i < n;++i) {
05169        --ex;
05170        if(i==0 && ex >= 0) {
05171            sprintf(psz, "%lu", (unsigned long)a->frac[i]);
05172            psz += strlen(psz);
05173        } else {
05174            m = BASE1;
05175            e = a->frac[i];
05176            while(m) {
05177                nn = e / m;
05178                *psz++ = (char)(nn + '0');
05179                e = e - nn * m;
05180                m /= 10;
05181            }
05182        }
05183        if(ex == 0) *psz++ = '.';
05184     }
05185     while(--ex>=0) {
05186        m = BASE;
05187        while(m/=10) *psz++ = '0';
05188        if(ex == 0) *psz++ = '.';
05189     }
05190     *psz = 0;
05191     while(psz[-1]=='0') *(--psz) = 0;
05192     if(psz[-1]=='.') sprintf(psz, "0");
05193     if(fFmt) VpFormatSt(pszSav, fFmt);
05194 }
05195 
05196 /*
05197  *  [Output]
05198  *   a[]  ... variable to be assigned the value.
05199  *  [Input]
05200  *   int_chr[]  ... integer part(may include '+/-').
05201  *   ni   ... number of characters in int_chr[],not including '+/-'.
05202  *   frac[]  ... fraction part.
05203  *   nf   ... number of characters in frac[].
05204  *   exp_chr[]  ... exponent part(including '+/-').
05205  *   ne   ... number of characters in exp_chr[],not including '+/-'.
05206  */
05207 VP_EXPORT int
05208 VpCtoV(Real *a, const char *int_chr, size_t ni, const char *frac, size_t nf, const char *exp_chr, size_t ne)
05209 {
05210     size_t i, j, ind_a, ma, mi, me;
05211     SIGNED_VALUE e, es, eb, ef;
05212     int  sign, signe, exponent_overflow;
05213 
05214     /* get exponent part */
05215     e = 0;
05216     ma = a->MaxPrec;
05217     mi = ni;
05218     me = ne;
05219     signe = 1;
05220     exponent_overflow = 0;
05221     memset(a->frac, 0, ma * sizeof(BDIGIT));
05222     if (ne > 0) {
05223         i = 0;
05224         if (exp_chr[0] == '-') {
05225             signe = -1;
05226             ++i;
05227             ++me;
05228         }
05229         else if (exp_chr[0] == '+') {
05230             ++i;
05231             ++me;
05232         }
05233         while (i < me) {
05234             es = e * (SIGNED_VALUE)BASE_FIG;
05235             e = e * 10 + exp_chr[i] - '0';
05236             if (es > (SIGNED_VALUE)(e*BASE_FIG)) {
05237                 exponent_overflow = 1;
05238                 e = es; /* keep sign */
05239                 break;
05240             }
05241             ++i;
05242         }
05243     }
05244 
05245     /* get integer part */
05246     i = 0;
05247     sign = 1;
05248     if(1 /*ni >= 0*/) {
05249         if(int_chr[0] == '-') {
05250             sign = -1;
05251             ++i;
05252             ++mi;
05253         } else if(int_chr[0] == '+') {
05254             ++i;
05255             ++mi;
05256         }
05257     }
05258 
05259     e = signe * e;        /* e: The value of exponent part. */
05260     e = e + ni;        /* set actual exponent size. */
05261 
05262     if (e > 0) signe = 1;
05263     else       signe = -1;
05264 
05265     /* Adjust the exponent so that it is the multiple of BASE_FIG. */
05266     j = 0;
05267     ef = 1;
05268     while (ef) {
05269         if (e >= 0) eb =  e;
05270         else        eb = -e;
05271         ef = eb / (SIGNED_VALUE)BASE_FIG;
05272         ef = eb - ef * (SIGNED_VALUE)BASE_FIG;
05273         if (ef) {
05274             ++j;        /* Means to add one more preceeding zero */
05275             ++e;
05276         }
05277     }
05278 
05279     eb = e / (SIGNED_VALUE)BASE_FIG;
05280 
05281     if (exponent_overflow) {
05282         int zero = 1;
05283         for (     ; i < mi && zero; i++) zero = int_chr[i] == '0';
05284         for (i = 0; i < nf && zero; i++) zero = frac[i] == '0';
05285         if (!zero && signe > 0) {
05286             VpSetInf(a, sign);
05287             VpException(VP_EXCEPTION_INFINITY, "exponent overflow",0);
05288         }
05289         else VpSetZero(a, sign);
05290         return 1;
05291     }
05292 
05293     ind_a = 0;
05294     while (i < mi) {
05295         a->frac[ind_a] = 0;
05296         while ((j < BASE_FIG) && (i < mi)) {
05297             a->frac[ind_a] = a->frac[ind_a] * 10 + int_chr[i] - '0';
05298             ++j;
05299             ++i;
05300         }
05301         if (i < mi) {
05302             ++ind_a;
05303             if (ind_a >= ma) goto over_flow;
05304             j = 0;
05305         }
05306     }
05307 
05308     /* get fraction part */
05309 
05310     i = 0;
05311     while(i < nf) {
05312         while((j < BASE_FIG) && (i < nf)) {
05313             a->frac[ind_a] = a->frac[ind_a] * 10 + frac[i] - '0';
05314             ++j;
05315             ++i;
05316         }
05317         if(i < nf) {
05318             ++ind_a;
05319             if(ind_a >= ma) goto over_flow;
05320             j = 0;
05321         }
05322     }
05323     goto Final;
05324 
05325 over_flow:
05326     rb_warn("Conversion from String to BigDecimal overflow (last few digits discarded).");
05327 
05328 Final:
05329     if (ind_a >= ma) ind_a = ma - 1;
05330     while (j < BASE_FIG) {
05331         a->frac[ind_a] = a->frac[ind_a] * 10;
05332         ++j;
05333     }
05334     a->Prec = ind_a + 1;
05335     a->exponent = eb;
05336     VpSetSign(a,sign);
05337     VpNmlz(a);
05338     return 1;
05339 }
05340 
05341 /*
05342  * [Input]
05343  *   *m  ... Real
05344  * [Output]
05345  *   *d  ... fraction part of m(d = 0.xxxxxxx). where # of 'x's is fig.
05346  *   *e  ... exponent of m.
05347  * DBLE_FIG ... Number of digits in a double variable.
05348  *
05349  *  m -> d*10**e, 0<d<BASE
05350  * [Returns]
05351  *   0 ... Zero
05352  *   1 ... Normal
05353  *   2 ... Infinity
05354  *  -1 ... NaN
05355  */
05356 VP_EXPORT int
05357 VpVtoD(double *d, SIGNED_VALUE *e, Real *m)
05358 {
05359     size_t ind_m, mm, fig;
05360     double div;
05361     int    f = 1;
05362 
05363     if(VpIsNaN(m)) {
05364         *d = VpGetDoubleNaN();
05365         *e = 0;
05366         f = -1; /* NaN */
05367         goto Exit;
05368     } else
05369     if(VpIsPosZero(m)) {
05370         *d = 0.0;
05371         *e = 0;
05372         f  = 0;
05373         goto Exit;
05374     } else
05375     if(VpIsNegZero(m)) {
05376         *d = VpGetDoubleNegZero();
05377         *e = 0;
05378         f  = 0;
05379         goto Exit;
05380     } else
05381     if(VpIsPosInf(m)) {
05382         *d = VpGetDoublePosInf();
05383         *e = 0;
05384         f  = 2;
05385         goto Exit;
05386     } else
05387     if(VpIsNegInf(m)) {
05388         *d = VpGetDoubleNegInf();
05389         *e = 0;
05390         f  = 2;
05391         goto Exit;
05392     }
05393     /* Normal number */
05394     fig =(DBLE_FIG + BASE_FIG - 1) / BASE_FIG;
05395     ind_m = 0;
05396     mm = Min(fig,(m->Prec));
05397     *d = 0.0;
05398     div = 1.;
05399     while(ind_m < mm) {
05400         div /= (double)BASE;
05401         *d = *d + (double)m->frac[ind_m++] * div;
05402     }
05403     *e = m->exponent * (SIGNED_VALUE)BASE_FIG;
05404     *d *= VpGetSign(m);
05405 
05406 Exit:
05407 #ifdef BIGDECIMAL_DEBUG
05408     if(gfDebug) {
05409         VPrint(stdout, " VpVtoD: m=%\n", m);
05410         printf("   d=%e * 10 **%ld\n", *d, *e);
05411         printf("   DBLE_FIG = %d\n", DBLE_FIG);
05412     }
05413 #endif /*BIGDECIMAL_DEBUG */
05414     return f;
05415 }
05416 
05417 /*
05418  * m <- d
05419  */
05420 VP_EXPORT void
05421 VpDtoV(Real *m, double d)
05422 {
05423     size_t ind_m, mm;
05424     SIGNED_VALUE ne;
05425     BDIGIT i;
05426     double  val, val2;
05427 
05428     if(isnan(d)) {
05429         VpSetNaN(m);
05430         goto Exit;
05431     }
05432     if(isinf(d)) {
05433         if(d>0.0) VpSetPosInf(m);
05434         else   VpSetNegInf(m);
05435         goto Exit;
05436     }
05437 
05438     if(d == 0.0) {
05439         VpSetZero(m,1);
05440         goto Exit;
05441     }
05442     val =(d > 0.) ? d :(-d);
05443     ne = 0;
05444     if(val >= 1.0) {
05445         while(val >= 1.0) {
05446             val /= (double)BASE;
05447             ++ne;
05448         }
05449     } else {
05450         val2 = 1.0 /(double)BASE;
05451         while(val < val2) {
05452             val *= (double)BASE;
05453             --ne;
05454         }
05455     }
05456     /* Now val = 0.xxxxx*BASE**ne */
05457 
05458     mm = m->MaxPrec;
05459     memset(m->frac, 0, mm * sizeof(BDIGIT));
05460     for(ind_m = 0;val > 0.0 && ind_m < mm;ind_m++) {
05461         val *= (double)BASE;
05462         i = (BDIGIT)val;
05463         val -= (double)i;
05464         m->frac[ind_m] = i;
05465     }
05466     if(ind_m >= mm) ind_m = mm - 1;
05467     VpSetSign(m, (d > 0.0) ? 1 : -1);
05468     m->Prec = ind_m + 1;
05469     m->exponent = ne;
05470 
05471     VpInternalRound(m, 0, (m->Prec > 0) ? m->frac[m->Prec-1] : 0,
05472                       (BDIGIT)(val*(double)BASE));
05473 
05474 Exit:
05475 #ifdef BIGDECIMAL_DEBUG
05476     if(gfDebug) {
05477         printf("VpDtoV d=%30.30e\n", d);
05478         VPrint(stdout, "  m=%\n", m);
05479     }
05480 #endif /* BIGDECIMAL_DEBUG */
05481     return;
05482 }
05483 
05484 /*
05485  *  m <- ival
05486  */
05487 #if 0  /* unused */
05488 VP_EXPORT void
05489 VpItoV(Real *m, SIGNED_VALUE ival)
05490 {
05491     size_t mm, ind_m;
05492     size_t val, v1, v2, v;
05493     int isign;
05494     SIGNED_VALUE ne;
05495 
05496     if(ival == 0) {
05497         VpSetZero(m,1);
05498         goto Exit;
05499     }
05500     isign = 1;
05501     val = ival;
05502     if(ival < 0) {
05503         isign = -1;
05504         val =(size_t)(-ival);
05505     }
05506     ne = 0;
05507     ind_m = 0;
05508     mm = m->MaxPrec;
05509     while(ind_m < mm) {
05510         m->frac[ind_m] = 0;
05511         ++ind_m;
05512     }
05513     ind_m = 0;
05514     while(val > 0) {
05515         if(val) {
05516          v1 = val;
05517          v2 = 1;
05518             while(v1 >= BASE) {
05519                 v1 /= BASE;
05520                 v2 *= BASE;
05521             }
05522             val = val - v2 * v1;
05523             v = v1;
05524         } else {
05525             v = 0;
05526         }
05527         m->frac[ind_m] = v;
05528         ++ind_m;
05529         ++ne;
05530     }
05531     m->Prec = ind_m - 1;
05532     m->exponent = ne;
05533     VpSetSign(m,isign);
05534     VpNmlz(m);
05535 
05536 Exit:
05537 #ifdef BIGDECIMAL_DEBUG
05538     if(gfDebug) {
05539         printf(" VpItoV i=%d\n", ival);
05540         VPrint(stdout, "  m=%\n", m);
05541     }
05542 #endif /* BIGDECIMAL_DEBUG */
05543     return;
05544 }
05545 #endif
05546 
05547 /*
05548  * y = SQRT(x),  y*y - x =>0
05549  */
05550 VP_EXPORT int
05551 VpSqrt(Real *y, Real *x)
05552 {
05553     Real *f = NULL;
05554     Real *r = NULL;
05555     size_t y_prec;
05556     SIGNED_VALUE n, e;
05557     SIGNED_VALUE prec;
05558     ssize_t nr;
05559     double val;
05560 
05561     /* Zero, NaN or Infinity ? */
05562     if(!VpHasVal(x)) {
05563         if(VpIsZero(x)||VpGetSign(x)>0) {
05564             VpAsgn(y,x,1);
05565             goto Exit;
05566         }
05567         VpSetNaN(y);
05568         return VpException(VP_EXCEPTION_OP,"(VpSqrt) SQRT(NaN or negative value)",0);
05569         goto Exit;
05570     }
05571 
05572      /* Negative ? */
05573     if(VpGetSign(x) < 0) {
05574         VpSetNaN(y);
05575         return VpException(VP_EXCEPTION_OP,"(VpSqrt) SQRT(negative value)",0);
05576     }
05577 
05578     /* One ? */
05579     if(VpIsOne(x)) {
05580         VpSetOne(y);
05581         goto Exit;
05582     }
05583 
05584     n = (SIGNED_VALUE)y->MaxPrec;
05585     if (x->MaxPrec > (size_t)n) n = (ssize_t)x->MaxPrec;
05586     /* allocate temporally variables  */
05587     f = VpAlloc(y->MaxPrec * (BASE_FIG + 2), "#1");
05588     r = VpAlloc((n + n) * (BASE_FIG + 2), "#1");
05589 
05590     nr = 0;
05591     y_prec = y->MaxPrec;
05592 
05593     prec = x->exponent - (ssize_t)y_prec;
05594     if (x->exponent > 0)
05595         ++prec;
05596     else
05597         --prec;
05598 
05599     VpVtoD(&val, &e, x);    /* val <- x  */
05600     e /= (SIGNED_VALUE)BASE_FIG;
05601     n = e / 2;
05602     if (e - n * 2 != 0) {
05603         val /= BASE;
05604         n = (e + 1) / 2;
05605     }
05606     VpDtoV(y, sqrt(val));    /* y <- sqrt(val) */
05607     y->exponent += n;
05608     n = (SIGNED_VALUE)((DBLE_FIG + BASE_FIG - 1) / BASE_FIG);
05609     y->MaxPrec = Min((size_t)n , y_prec);
05610     f->MaxPrec = y->MaxPrec + 1;
05611     n = (SIGNED_VALUE)(y_prec * BASE_FIG);
05612     if (n < (SIGNED_VALUE)maxnr) n = (SIGNED_VALUE)maxnr;
05613     do {
05614         y->MaxPrec *= 2;
05615         if (y->MaxPrec > y_prec) y->MaxPrec = y_prec;
05616         f->MaxPrec = y->MaxPrec;
05617         VpDivd(f, r, x, y);     /* f = x/y    */
05618         VpAddSub(r, f, y, -1);  /* r = f - y  */
05619         VpMult(f, VpPt5, r);    /* f = 0.5*r  */
05620         if(VpIsZero(f))         goto converge;
05621         VpAddSub(r, f, y, 1);   /* r = y + f  */
05622         VpAsgn(y, r, 1);        /* y = r      */
05623         if(f->exponent <= prec) goto converge;
05624     } while(++nr < n);
05625     /* */
05626 #ifdef BIGDECIMAL_DEBUG
05627     if(gfDebug) {
05628         printf("ERROR(VpSqrt): did not converge within %ld iterations.\n",
05629             nr);
05630     }
05631 #endif /* BIGDECIMAL_DEBUG */
05632     y->MaxPrec = y_prec;
05633 
05634 converge:
05635     VpChangeSign(y, 1);
05636 #ifdef BIGDECIMAL_DEBUG
05637     if(gfDebug) {
05638         VpMult(r, y, y);
05639         VpAddSub(f, x, r, -1);
05640         printf("VpSqrt: iterations = %"PRIdSIZE"\n", nr);
05641         VPrint(stdout, "  y =% \n", y);
05642         VPrint(stdout, "  x =% \n", x);
05643         VPrint(stdout, "  x-y*y = % \n", f);
05644     }
05645 #endif /* BIGDECIMAL_DEBUG */
05646     y->MaxPrec = y_prec;
05647 
05648 Exit:
05649     VpFree(f);
05650     VpFree(r);
05651     return 1;
05652 }
05653 
05654 /*
05655  *
05656  * nf: digit position for operation.
05657  *
05658  */
05659 VP_EXPORT int
05660 VpMidRound(Real *y, unsigned short f, ssize_t nf)
05661 /*
05662  * Round reletively from the decimal point.
05663  *    f: rounding mode
05664  *   nf: digit location to round from the the decimal point.
05665  */
05666 {
05667     /* fracf: any positive digit under rounding position? */
05668     /* fracf_1further: any positive digits under one further than the rounding position? */
05669     /* exptoadd: number of digits needed to compensate negative nf */
05670     int fracf, fracf_1further;
05671     ssize_t n,i,ix,ioffset, exptoadd;
05672     BDIGIT v, shifter;
05673     BDIGIT div;
05674 
05675     nf += y->exponent * (ssize_t)BASE_FIG;
05676     exptoadd=0;
05677     if (nf < 0) {
05678         /* rounding position too left(large). */
05679         if((f!=VP_ROUND_CEIL) && (f!=VP_ROUND_FLOOR)) {
05680             VpSetZero(y,VpGetSign(y)); /* truncate everything */
05681             return 0;
05682         }
05683         exptoadd = -nf;
05684         nf = 0;
05685     }
05686 
05687     ix = nf / (ssize_t)BASE_FIG;
05688     if ((size_t)ix >= y->Prec) return 0;  /* rounding position too right(small). */
05689     v = y->frac[ix];
05690 
05691     ioffset = nf - ix*(ssize_t)BASE_FIG;
05692     n = (ssize_t)BASE_FIG - ioffset - 1;
05693     for (shifter=1,i=0; i<n; ++i) shifter *= 10;
05694 
05695     /* so the representation used (in y->frac) is an array of BDIGIT, where
05696        each BDIGIT contains a value between 0 and BASE-1, consisting of BASE_FIG
05697        decimal places.
05698 
05699        (that numbers of decimal places are typed as ssize_t is somewhat confusing)
05700 
05701        nf is now position (in decimal places) of the digit from the start of
05702           the array.
05703        ix is the position (in BDIGITS) of the BDIGIT containing the decimal digit,
05704           from the start of the array.
05705        v is the value of this BDIGIT
05706        ioffset is the number of extra decimal places along of this decimal digit
05707           within v.
05708        n is the number of decimal digits remaining within v after this decimal digit
05709        shifter is 10**n,
05710        v % shifter are the remaining digits within v
05711        v % (shifter * 10) are the digit together with the remaining digits within v
05712        v / shifter are the digit's predecessors together with the digit
05713        div = v / shifter / 10 is just the digit's precessors
05714        (v / shifter) - div*10 is just the digit, which is what v ends up being reassigned to.
05715     */
05716 
05717     fracf = (v % (shifter * 10) > 0);
05718     fracf_1further = ((v % shifter) > 0);
05719 
05720     v /= shifter;
05721     div = v / 10;
05722     v = v - div*10;
05723     /* now v is just the digit required.
05724        now fracf is whether the digit or any of the remaining digits within v are non-zero
05725        now fracf_1further is whether any of the remaining digits within v are non-zero
05726     */
05727 
05728     /* now check all the remaining BDIGITS for zero-ness a whole BDIGIT at a time.
05729        if we spot any non-zeroness, that means that we foudn a positive digit under
05730        rounding position, and we also found a positive digit under one further than
05731        the rounding position, so both searches (to see if any such non-zero digit exists)
05732        can stop */
05733 
05734     for (i=ix+1; (size_t)i < y->Prec; i++) {
05735         if (y->frac[i] % BASE) {
05736             fracf = fracf_1further = 1;
05737             break;
05738         }
05739     }
05740 
05741     /* now fracf = does any positive digit exist under the rounding position?
05742        now fracf_1further = does any positive digit exist under one further than the
05743        rounding position?
05744        now v = the first digit under the rounding position */
05745 
05746     /* drop digits after pointed digit */
05747     memset(y->frac+ix+1, 0, (y->Prec - (ix+1)) * sizeof(BDIGIT));
05748 
05749     switch(f) {
05750     case VP_ROUND_DOWN: /* Truncate */
05751          break;
05752     case VP_ROUND_UP:   /* Roundup */
05753         if (fracf) ++div;
05754         break;
05755     case VP_ROUND_HALF_UP:
05756         if (v>=5) ++div;
05757         break;
05758     case VP_ROUND_HALF_DOWN:
05759         if (v > 5 || (v == 5 && fracf_1further)) ++div;
05760         break;
05761     case VP_ROUND_CEIL:
05762         if (fracf && (VpGetSign(y)>0)) ++div;
05763         break;
05764     case VP_ROUND_FLOOR:
05765         if (fracf && (VpGetSign(y)<0)) ++div;
05766         break;
05767     case VP_ROUND_HALF_EVEN: /* Banker's rounding */
05768         if (v > 5) ++div;
05769         else if (v == 5) {
05770             if (fracf_1further) {
05771               ++div;
05772             }
05773             else {
05774                 if (ioffset == 0) {
05775                     /* v is the first decimal digit of its BDIGIT;
05776                        need to grab the previous BDIGIT if present
05777                        to check for evenness of the previous decimal
05778                        digit (which is same as that of the BDIGIT since
05779                        base 10 has a factor of 2) */
05780                     if (ix && (y->frac[ix-1] % 2)) ++div;
05781                 }
05782                 else {
05783                     if (div % 2) ++div;
05784                 }
05785             }
05786         }
05787         break;
05788     }
05789     for (i=0; i<=n; ++i) div *= 10;
05790     if (div>=BASE) {
05791         if(ix) {
05792             y->frac[ix] = 0;
05793             VpRdup(y,ix);
05794         } else {
05795             short s = VpGetSign(y);
05796             SIGNED_VALUE e = y->exponent;
05797             VpSetOne(y);
05798             VpSetSign(y, s);
05799             y->exponent = e+1;
05800         }
05801     } else {
05802         y->frac[ix] = div;
05803         VpNmlz(y);
05804     }
05805     if (exptoadd > 0) {
05806         y->exponent += (SIGNED_VALUE)(exptoadd/BASE_FIG);
05807         exptoadd %= (ssize_t)BASE_FIG;
05808         for(i=0;i<exptoadd;i++) {
05809             y->frac[0] *= 10;
05810             if (y->frac[0] >= BASE) {
05811                 y->frac[0] /= BASE;
05812                 y->exponent++;
05813             }
05814         }
05815     }
05816     return 1;
05817 }
05818 
05819 VP_EXPORT int
05820 VpLeftRound(Real *y, unsigned short f, ssize_t nf)
05821 /*
05822  * Round from the left hand side of the digits.
05823  */
05824 {
05825     BDIGIT v;
05826     if (!VpHasVal(y)) return 0; /* Unable to round */
05827     v = y->frac[0];
05828     nf -= VpExponent(y)*(ssize_t)BASE_FIG;
05829     while ((v /= 10) != 0) nf--;
05830     nf += (ssize_t)BASE_FIG-1;
05831     return VpMidRound(y,f,nf);
05832 }
05833 
05834 VP_EXPORT int
05835 VpActiveRound(Real *y, Real *x, unsigned short f, ssize_t nf)
05836 {
05837     /* First,assign whole value in truncation mode */
05838     if (VpAsgn(y, x, 10) <= 1) return 0; /* Zero,NaN,or Infinity */
05839     return VpMidRound(y,f,nf);
05840 }
05841 
05842 static int
05843 VpLimitRound(Real *c, size_t ixDigit)
05844 {
05845     size_t ix = VpGetPrecLimit();
05846     if(!VpNmlz(c))    return -1;
05847     if(!ix)           return 0;
05848     if(!ixDigit) ixDigit = c->Prec-1;
05849     if((ix+BASE_FIG-1)/BASE_FIG > ixDigit+1) return 0;
05850     return VpLeftRound(c, VpGetRoundMode(), (ssize_t)ix);
05851 }
05852 
05853 /* If I understand correctly, this is only ever used to round off the final decimal
05854    digit of precision */
05855 static void
05856 VpInternalRound(Real *c, size_t ixDigit, BDIGIT vPrev, BDIGIT v)
05857 {
05858     int f = 0;
05859 
05860     unsigned short const rounding_mode = VpGetRoundMode();
05861 
05862     if (VpLimitRound(c, ixDigit)) return;
05863     if (!v) return;
05864 
05865     v /= BASE1;
05866     switch (rounding_mode) {
05867     case VP_ROUND_DOWN:
05868         break;
05869     case VP_ROUND_UP:
05870         if (v) f = 1;
05871         break;
05872     case VP_ROUND_HALF_UP:
05873         if (v >= 5) f = 1;
05874         break;
05875     case VP_ROUND_HALF_DOWN:
05876         /* this is ok - because this is the last digit of precision,
05877            the case where v == 5 and some further digits are nonzero
05878            will never occur */
05879         if (v >= 6) f = 1;
05880         break;
05881     case VP_ROUND_CEIL:
05882         if (v && (VpGetSign(c) > 0)) f = 1;
05883         break;
05884     case VP_ROUND_FLOOR:
05885         if (v && (VpGetSign(c) < 0)) f = 1;
05886         break;
05887     case VP_ROUND_HALF_EVEN:  /* Banker's rounding */
05888         /* as per VP_ROUND_HALF_DOWN, because this is the last digit of precision,
05889            there is no case to worry about where v == 5 and some further digits are nonzero */
05890         if (v > 5) f = 1;
05891         else if (v == 5 && vPrev % 2) f = 1;
05892         break;
05893     }
05894     if (f) {
05895         VpRdup(c, ixDigit);
05896         VpNmlz(c);
05897     }
05898 }
05899 
05900 /*
05901  *  Rounds up m(plus one to final digit of m).
05902  */
05903 static int
05904 VpRdup(Real *m, size_t ind_m)
05905 {
05906     BDIGIT carry;
05907 
05908     if (!ind_m) ind_m = m->Prec;
05909 
05910     carry = 1;
05911     while (carry > 0 && (ind_m--)) {
05912         m->frac[ind_m] += carry;
05913         if (m->frac[ind_m] >= BASE) m->frac[ind_m] -= BASE;
05914         else                        carry = 0;
05915     }
05916     if(carry > 0) {        /* Overflow,count exponent and set fraction part be 1  */
05917         if (!AddExponent(m, 1)) return 0;
05918         m->Prec = m->frac[0] = 1;
05919     } else {
05920         VpNmlz(m);
05921     }
05922     return 1;
05923 }
05924 
05925 /*
05926  *  y = x - fix(x)
05927  */
05928 VP_EXPORT void
05929 VpFrac(Real *y, Real *x)
05930 {
05931     size_t my, ind_y, ind_x;
05932 
05933     if(!VpHasVal(x)) {
05934         VpAsgn(y,x,1);
05935         goto Exit;
05936     }
05937 
05938     if (x->exponent > 0 && (size_t)x->exponent >= x->Prec) {
05939         VpSetZero(y,VpGetSign(x));
05940         goto Exit;
05941     }
05942     else if(x->exponent <= 0) {
05943         VpAsgn(y, x, 1);
05944         goto Exit;
05945     }
05946 
05947     /* satisfy: x->exponent > 0 */
05948 
05949     y->Prec = x->Prec - (size_t)x->exponent;
05950     y->Prec = Min(y->Prec, y->MaxPrec);
05951     y->exponent = 0;
05952     VpSetSign(y,VpGetSign(x));
05953     ind_y = 0;
05954     my = y->Prec;
05955     ind_x = x->exponent;
05956     while(ind_y < my) {
05957         y->frac[ind_y] = x->frac[ind_x];
05958         ++ind_y;
05959         ++ind_x;
05960     }
05961     VpNmlz(y);
05962 
05963 Exit:
05964 #ifdef BIGDECIMAL_DEBUG
05965     if(gfDebug) {
05966         VPrint(stdout, "VpFrac y=%\n", y);
05967         VPrint(stdout, "    x=%\n", x);
05968     }
05969 #endif /* BIGDECIMAL_DEBUG */
05970     return;
05971 }
05972 
05973 /*
05974  *   y = x ** n
05975  */
05976 VP_EXPORT int
05977 VpPower(Real *y, Real *x, SIGNED_VALUE n)
05978 {
05979     size_t s, ss;
05980     ssize_t sign;
05981     Real *w1 = NULL;
05982     Real *w2 = NULL;
05983 
05984     if(VpIsZero(x)) {
05985         if(n==0) {
05986            VpSetOne(y);
05987            goto Exit;
05988         }
05989         sign = VpGetSign(x);
05990         if(n<0) {
05991            n = -n;
05992            if(sign<0) sign = (n%2)?(-1):(1);
05993            VpSetInf (y,sign);
05994         } else {
05995            if(sign<0) sign = (n%2)?(-1):(1);
05996            VpSetZero(y,sign);
05997         }
05998         goto Exit;
05999     }
06000     if(VpIsNaN(x)) {
06001         VpSetNaN(y);
06002         goto Exit;
06003     }
06004     if(VpIsInf(x)) {
06005         if(n==0) {
06006             VpSetOne(y);
06007             goto Exit;
06008         }
06009         if(n>0) {
06010             VpSetInf(y, (n%2==0 || VpIsPosInf(x)) ? 1 : -1);
06011             goto Exit;
06012         }
06013         VpSetZero(y, (n%2==0 || VpIsPosInf(x)) ? 1 : -1);
06014         goto Exit;
06015     }
06016 
06017     if((x->exponent == 1) &&(x->Prec == 1) &&(x->frac[0] == 1)) {
06018         /* abs(x) = 1 */
06019         VpSetOne(y);
06020         if(VpGetSign(x) > 0) goto Exit;
06021         if((n % 2) == 0) goto Exit;
06022         VpSetSign(y, -1);
06023         goto Exit;
06024     }
06025 
06026     if(n > 0) sign = 1;
06027     else if(n < 0) {
06028         sign = -1;
06029         n = -n;
06030     } else {
06031         VpSetOne(y);
06032         goto Exit;
06033     }
06034 
06035     /* Allocate working variables  */
06036 
06037     w1 = VpAlloc((y->MaxPrec + 2) * BASE_FIG, "#0");
06038     w2 = VpAlloc((w1->MaxPrec * 2 + 1) * BASE_FIG, "#0");
06039     /* calculation start */
06040 
06041     VpAsgn(y, x, 1);
06042     --n;
06043     while(n > 0) {
06044         VpAsgn(w1, x, 1);
06045         s = 1;
06046         while (ss = s, (s += s) <= (size_t)n) {
06047             VpMult(w2, w1, w1);
06048             VpAsgn(w1, w2, 1);
06049         }
06050         n -= (SIGNED_VALUE)ss;
06051         VpMult(w2, y, w1);
06052         VpAsgn(y, w2, 1);
06053     }
06054     if(sign < 0) {
06055         VpDivd(w1, w2, VpConstOne, y);
06056         VpAsgn(y, w1, 1);
06057     }
06058 
06059 Exit:
06060 #ifdef BIGDECIMAL_DEBUG
06061     if(gfDebug) {
06062         VPrint(stdout, "VpPower y=%\n", y);
06063         VPrint(stdout, "VpPower x=%\n", x);
06064         printf("  n=%d\n", n);
06065     }
06066 #endif /* BIGDECIMAL_DEBUG */
06067     VpFree(w2);
06068     VpFree(w1);
06069     return 1;
06070 }
06071 
06072 #ifdef BIGDECIMAL_DEBUG
06073 int
06074 VpVarCheck(Real * v)
06075 /*
06076  * Checks the validity of the Real variable v.
06077  * [Input]
06078  *   v ... Real *, variable to be checked.
06079  * [Returns]
06080  *   0  ... correct v.
06081  *   other ... error
06082  */
06083 {
06084     size_t i;
06085 
06086     if(v->MaxPrec <= 0) {
06087         printf("ERROR(VpVarCheck): Illegal Max. Precision(=%"PRIuSIZE")\n",
06088             v->MaxPrec);
06089         return 1;
06090     }
06091     if((v->Prec <= 0) ||((v->Prec) >(v->MaxPrec))) {
06092         printf("ERROR(VpVarCheck): Illegal Precision(=%"PRIuSIZE")\n", v->Prec);
06093         printf("       Max. Prec.=%"PRIuSIZE"\n", v->MaxPrec);
06094         return 2;
06095     }
06096     for(i = 0; i < v->Prec; ++i) {
06097         if((v->frac[i] >= BASE)) {
06098             printf("ERROR(VpVarCheck): Illegal fraction\n");
06099             printf("       Frac[%"PRIuSIZE"]=%lu\n", i, v->frac[i]);
06100             printf("       Prec.   =%"PRIuSIZE"\n", v->Prec);
06101             printf("       Exp. =%"PRIdVALUE"\n", v->exponent);
06102             printf("       BASE =%lu\n", BASE);
06103             return 3;
06104         }
06105     }
06106     return 0;
06107 }
06108 #endif /* BIGDECIMAL_DEBUG */
06109