PageRenderTime 254ms CodeModel.GetById 38ms RepoModel.GetById 9ms app.codeStats 1ms

/ext/bigdecimal/bigdecimal.c

https://github.com/wanabe/ruby
C | 7054 lines | 4997 code | 673 blank | 1384 comment | 1210 complexity | f74247c34b39931c1486171c69397292 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, 0BSD, Unlicense, GPL-2.0, BSD-3-Clause
  1. /*
  2. *
  3. * Ruby BigDecimal(Variable decimal precision) extension library.
  4. *
  5. * Copyright(C) 2002 by Shigeo Kobayashi(shigeo@tinyforest.gr.jp)
  6. *
  7. */
  8. /* #define BIGDECIMAL_DEBUG 1 */
  9. #ifdef BIGDECIMAL_DEBUG
  10. # define BIGDECIMAL_ENABLE_VPRINT 1
  11. #endif
  12. #include "bigdecimal.h"
  13. #include "ruby/util.h"
  14. #ifndef BIGDECIMAL_DEBUG
  15. # undef NDEBUG
  16. # define NDEBUG
  17. #endif
  18. #include <assert.h>
  19. #include <ctype.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <string.h>
  23. #include <errno.h>
  24. #include <math.h>
  25. #ifdef HAVE_IEEEFP_H
  26. #include <ieeefp.h>
  27. #endif
  28. #include "bits.h"
  29. #include "static_assert.h"
  30. /* #define ENABLE_NUMERIC_STRING */
  31. #define SIGNED_VALUE_MAX INTPTR_MAX
  32. #define SIGNED_VALUE_MIN INTPTR_MIN
  33. #define MUL_OVERFLOW_SIGNED_VALUE_P(a, b) MUL_OVERFLOW_SIGNED_INTEGER_P(a, b, SIGNED_VALUE_MIN, SIGNED_VALUE_MAX)
  34. VALUE rb_cBigDecimal;
  35. VALUE rb_mBigMath;
  36. static ID id_BigDecimal_exception_mode;
  37. static ID id_BigDecimal_rounding_mode;
  38. static ID id_BigDecimal_precision_limit;
  39. static ID id_up;
  40. static ID id_down;
  41. static ID id_truncate;
  42. static ID id_half_up;
  43. static ID id_default;
  44. static ID id_half_down;
  45. static ID id_half_even;
  46. static ID id_banker;
  47. static ID id_ceiling;
  48. static ID id_ceil;
  49. static ID id_floor;
  50. static ID id_to_r;
  51. static ID id_eq;
  52. static ID id_half;
  53. /* MACRO's to guard objects from GC by keeping them in stack */
  54. #ifdef RBIMPL_ATTR_MAYBE_UNUSED
  55. #define ENTER(n) RBIMPL_ATTR_MAYBE_UNUSED() volatile VALUE vStack[n];int iStack=0
  56. #else
  57. #define ENTER(n) volatile VALUE RB_UNUSED_VAR(vStack[n]);int iStack=0
  58. #endif
  59. #define PUSH(x) (vStack[iStack++] = (VALUE)(x))
  60. #define SAVE(p) PUSH((p)->obj)
  61. #define GUARD_OBJ(p,y) ((p)=(y), SAVE(p))
  62. #define BASE_FIG BIGDECIMAL_COMPONENT_FIGURES
  63. #define BASE BIGDECIMAL_BASE
  64. #define HALF_BASE (BASE/2)
  65. #define BASE1 (BASE/10)
  66. #define LOG10_2 0.3010299956639812
  67. #ifndef RRATIONAL_ZERO_P
  68. # define RRATIONAL_ZERO_P(x) (FIXNUM_P(rb_rational_num(x)) && \
  69. FIX2LONG(rb_rational_num(x)) == 0)
  70. #endif
  71. #ifndef RRATIONAL_NEGATIVE_P
  72. # define RRATIONAL_NEGATIVE_P(x) RTEST(rb_funcall((x), '<', 1, INT2FIX(0)))
  73. #endif
  74. #ifndef DECIMAL_SIZE_OF_BITS
  75. #define DECIMAL_SIZE_OF_BITS(n) (((n) * 3010 + 9998) / 9999)
  76. /* an approximation of ceil(n * log10(2)), upto 65536 at least */
  77. #endif
  78. #ifdef PRIsVALUE
  79. # define RB_OBJ_CLASSNAME(obj) rb_obj_class(obj)
  80. # define RB_OBJ_STRING(obj) (obj)
  81. #else
  82. # define PRIsVALUE "s"
  83. # define RB_OBJ_CLASSNAME(obj) rb_obj_classname(obj)
  84. # define RB_OBJ_STRING(obj) StringValueCStr(obj)
  85. #endif
  86. #define BIGDECIMAL_POSITIVE_P(bd) ((bd)->sign > 0)
  87. #define BIGDECIMAL_NEGATIVE_P(bd) ((bd)->sign < 0)
  88. /*
  89. * ================== Ruby Interface part ==========================
  90. */
  91. #define DoSomeOne(x,y,f) rb_num_coerce_bin(x,y,f)
  92. /*
  93. * VP routines used in BigDecimal part
  94. */
  95. static unsigned short VpGetException(void);
  96. static void VpSetException(unsigned short f);
  97. static void VpInternalRound(Real *c, size_t ixDigit, DECDIG vPrev, DECDIG v);
  98. static int VpLimitRound(Real *c, size_t ixDigit);
  99. static Real *VpCopy(Real *pv, Real const* const x);
  100. #ifdef BIGDECIMAL_ENABLE_VPRINT
  101. static int VPrint(FILE *fp,const char *cntl_chr,Real *a);
  102. #endif
  103. /*
  104. * **** BigDecimal part ****
  105. */
  106. static VALUE BigDecimal_nan(void);
  107. static VALUE BigDecimal_positive_infinity(void);
  108. static VALUE BigDecimal_negative_infinity(void);
  109. static VALUE BigDecimal_positive_zero(void);
  110. static VALUE BigDecimal_negative_zero(void);
  111. static void
  112. BigDecimal_delete(void *pv)
  113. {
  114. VpFree(pv);
  115. }
  116. static size_t
  117. BigDecimal_memsize(const void *ptr)
  118. {
  119. const Real *pv = ptr;
  120. return (sizeof(*pv) + pv->MaxPrec * sizeof(DECDIG));
  121. }
  122. #ifndef HAVE_RB_EXT_RACTOR_SAFE
  123. # undef RUBY_TYPED_FROZEN_SHAREABLE
  124. # define RUBY_TYPED_FROZEN_SHAREABLE 0
  125. #endif
  126. static const rb_data_type_t BigDecimal_data_type = {
  127. "BigDecimal",
  128. { 0, BigDecimal_delete, BigDecimal_memsize, },
  129. #ifdef RUBY_TYPED_FREE_IMMEDIATELY
  130. 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_FROZEN_SHAREABLE
  131. #endif
  132. };
  133. static inline int
  134. is_kind_of_BigDecimal(VALUE const v)
  135. {
  136. return rb_typeddata_is_kind_of(v, &BigDecimal_data_type);
  137. }
  138. static void
  139. VpCheckException(Real *p, bool always)
  140. {
  141. if (VpIsNaN(p)) {
  142. VpException(VP_EXCEPTION_NaN, "Computation results to 'NaN'(Not a Number)", always);
  143. }
  144. else if (VpIsPosInf(p)) {
  145. VpException(VP_EXCEPTION_INFINITY, "Computation results to 'Infinity'", always);
  146. }
  147. else if (VpIsNegInf(p)) {
  148. VpException(VP_EXCEPTION_INFINITY, "Computation results to '-Infinity'", always);
  149. }
  150. }
  151. static VALUE
  152. VpCheckGetValue(Real *p)
  153. {
  154. VpCheckException(p, false);
  155. return p->obj;
  156. }
  157. NORETURN(static void cannot_be_coerced_into_BigDecimal(VALUE, VALUE));
  158. static void
  159. cannot_be_coerced_into_BigDecimal(VALUE exc_class, VALUE v)
  160. {
  161. VALUE str;
  162. if (rb_special_const_p(v)) {
  163. str = rb_inspect(v);
  164. }
  165. else {
  166. str = rb_class_name(rb_obj_class(v));
  167. }
  168. str = rb_str_cat2(rb_str_dup(str), " can't be coerced into BigDecimal");
  169. rb_exc_raise(rb_exc_new3(exc_class, str));
  170. }
  171. static inline VALUE BigDecimal_div2(VALUE, VALUE, VALUE);
  172. static VALUE rb_inum_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
  173. static VALUE rb_float_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
  174. static VALUE rb_rational_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
  175. static VALUE rb_cstr_convert_to_BigDecimal(const char *c_str, size_t digs, int raise_exception);
  176. static VALUE rb_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception);
  177. static Real*
  178. GetVpValueWithPrec(VALUE v, long prec, int must)
  179. {
  180. const size_t digs = prec < 0 ? SIZE_MAX : (size_t)prec;
  181. switch(TYPE(v)) {
  182. case T_FLOAT:
  183. v = rb_float_convert_to_BigDecimal(v, digs, must);
  184. break;
  185. case T_RATIONAL:
  186. v = rb_rational_convert_to_BigDecimal(v, digs, must);
  187. break;
  188. case T_DATA:
  189. if (!is_kind_of_BigDecimal(v)) {
  190. goto SomeOneMayDoIt;
  191. }
  192. break;
  193. case T_FIXNUM: {
  194. char szD[128];
  195. sprintf(szD, "%ld", FIX2LONG(v));
  196. v = rb_cstr_convert_to_BigDecimal(szD, VpBaseFig() * 2 + 1, must);
  197. break;
  198. }
  199. #ifdef ENABLE_NUMERIC_STRING
  200. case T_STRING: {
  201. const char *c_str = StringValueCStr(v);
  202. v = rb_cstr_convert_to_BigDecimal(c_str, RSTRING_LEN(v) + VpBaseFig() + 1, must);
  203. break;
  204. }
  205. #endif /* ENABLE_NUMERIC_STRING */
  206. case T_BIGNUM: {
  207. VALUE bg = rb_big2str(v, 10);
  208. v = rb_cstr_convert_to_BigDecimal(RSTRING_PTR(bg), RSTRING_LEN(bg) + VpBaseFig() + 1, must);
  209. RB_GC_GUARD(bg);
  210. break;
  211. }
  212. default:
  213. goto SomeOneMayDoIt;
  214. }
  215. Real *vp;
  216. TypedData_Get_Struct(v, Real, &BigDecimal_data_type, vp);
  217. return vp;
  218. SomeOneMayDoIt:
  219. if (must) {
  220. cannot_be_coerced_into_BigDecimal(rb_eTypeError, v);
  221. }
  222. return NULL; /* NULL means to coerce */
  223. }
  224. static Real*
  225. GetVpValue(VALUE v, int must)
  226. {
  227. return GetVpValueWithPrec(v, -1, must);
  228. }
  229. /* call-seq:
  230. * BigDecimal.double_fig
  231. *
  232. * The BigDecimal.double_fig class method returns the number of digits a
  233. * Float number is allowed to have. The result depends upon the CPU and OS
  234. * in use.
  235. */
  236. static VALUE
  237. BigDecimal_double_fig(VALUE self)
  238. {
  239. return INT2FIX(VpDblFig());
  240. }
  241. /* call-seq:
  242. * big_decimal.precs -> array
  243. *
  244. * Returns an Array of two Integer values that represent platform-dependent
  245. * internal storage properties.
  246. *
  247. * This method is deprecated and will be removed in the future.
  248. * Instead, use BigDecimal#n_significant_digits for obtaining the number of
  249. * significant digits in scientific notation, and BigDecimal#precision for
  250. * obtaining the number of digits in decimal notation.
  251. *
  252. * BigDecimal('5').precs #=> [9, 18]
  253. */
  254. static VALUE
  255. BigDecimal_prec(VALUE self)
  256. {
  257. ENTER(1);
  258. Real *p;
  259. VALUE obj;
  260. rb_category_warn(RB_WARN_CATEGORY_DEPRECATED,
  261. "BigDecimal#precs is deprecated and will be removed in the future; "
  262. "use BigDecimal#precision instead.");
  263. GUARD_OBJ(p, GetVpValue(self, 1));
  264. obj = rb_assoc_new(SIZET2NUM(p->Prec*VpBaseFig()),
  265. SIZET2NUM(p->MaxPrec*VpBaseFig()));
  266. return obj;
  267. }
  268. /*
  269. * call-seq:
  270. * big_decimal.precision -> intreger
  271. *
  272. * Returns the number of decimal digits in this number.
  273. *
  274. * Example:
  275. *
  276. * BigDecimal("0").precision # => 0
  277. * BigDecimal("1").precision # => 1
  278. * BigDecimal("-1e20").precision # => 21
  279. * BigDecimal("1e-20").precision # => 20
  280. * BigDecimal("Infinity").precision # => 0
  281. * BigDecimal("-Infinity").precision # => 0
  282. * BigDecimal("NaN").precision # => 0
  283. */
  284. static VALUE
  285. BigDecimal_precision(VALUE self)
  286. {
  287. ENTER(1);
  288. Real *p;
  289. GUARD_OBJ(p, GetVpValue(self, 1));
  290. /*
  291. * The most significant digit is frac[0], and the least significant digit is frac[Prec-1].
  292. * When the exponent is zero, the decimal point is located just before frac[0].
  293. * When the exponent is negative, the decimal point moves to leftward.
  294. * Conversely, when the exponent is positive, the decimal point moves to rightward.
  295. *
  296. * | frac[0] frac[1] frac[2] . frac[3] frac[4] ... frac[Prec-1]
  297. * |------------------------> exponent == 3
  298. */
  299. ssize_t ex = p->exponent;
  300. ssize_t precision = 0;
  301. if (ex < 0) {
  302. precision = (-ex + 1) * BASE_FIG; /* 1 is for p->frac[0] */
  303. ex = 0;
  304. }
  305. else if (p->Prec > 0) {
  306. DECDIG x = p->frac[0];
  307. for (precision = 0; x > 0; x /= 10) {
  308. ++precision;
  309. }
  310. }
  311. if (ex > (ssize_t)p->Prec) {
  312. precision += (ex - 1) * BASE_FIG;
  313. }
  314. else if (p->Prec > 0) {
  315. ssize_t n = (ssize_t)p->Prec - 1;
  316. while (n > 0 && p->frac[n] == 0) --n;
  317. precision += n * BASE_FIG;
  318. if (ex < (ssize_t)p->Prec) {
  319. DECDIG x = p->frac[n];
  320. for (; x > 0 && x % 10 == 0; x /= 10) {
  321. --precision;
  322. }
  323. }
  324. }
  325. return SSIZET2NUM(precision);
  326. }
  327. static VALUE
  328. BigDecimal_n_significant_digits(VALUE self)
  329. {
  330. ENTER(1);
  331. Real *p;
  332. GUARD_OBJ(p, GetVpValue(self, 1));
  333. ssize_t n = p->Prec;
  334. while (n > 0 && p->frac[n-1] == 0) --n;
  335. if (n <= 0) {
  336. return INT2FIX(0);
  337. }
  338. int nlz, ntz;
  339. DECDIG x = p->frac[0];
  340. for (nlz = BASE_FIG; x > 0; x /= 10) --nlz;
  341. x = p->frac[n-1];
  342. for (ntz = 0; x > 0 && x % 10 == 0; x /= 10) ++ntz;
  343. ssize_t n_digits = BASE_FIG * n - nlz - ntz;
  344. return SSIZET2NUM(n_digits);
  345. }
  346. /*
  347. * call-seq: hash
  348. *
  349. * Creates a hash for this BigDecimal.
  350. *
  351. * Two BigDecimals with equal sign,
  352. * fractional part and exponent have the same hash.
  353. */
  354. static VALUE
  355. BigDecimal_hash(VALUE self)
  356. {
  357. ENTER(1);
  358. Real *p;
  359. st_index_t hash;
  360. GUARD_OBJ(p, GetVpValue(self, 1));
  361. hash = (st_index_t)p->sign;
  362. /* hash!=2: the case for 0(1),NaN(0) or +-Infinity(3) is sign itself */
  363. if(hash == 2 || hash == (st_index_t)-2) {
  364. hash ^= rb_memhash(p->frac, sizeof(DECDIG)*p->Prec);
  365. hash += p->exponent;
  366. }
  367. return ST2FIX(hash);
  368. }
  369. /*
  370. * call-seq: _dump
  371. *
  372. * Method used to provide marshalling support.
  373. *
  374. * inf = BigDecimal('Infinity')
  375. * #=> Infinity
  376. * BigDecimal._load(inf._dump)
  377. * #=> Infinity
  378. *
  379. * See the Marshal module.
  380. */
  381. static VALUE
  382. BigDecimal_dump(int argc, VALUE *argv, VALUE self)
  383. {
  384. ENTER(5);
  385. Real *vp;
  386. char *psz;
  387. VALUE dummy;
  388. volatile VALUE dump;
  389. rb_scan_args(argc, argv, "01", &dummy);
  390. GUARD_OBJ(vp,GetVpValue(self, 1));
  391. dump = rb_str_new(0, VpNumOfChars(vp, "E")+50);
  392. psz = RSTRING_PTR(dump);
  393. sprintf(psz, "%"PRIuSIZE":", VpMaxPrec(vp)*VpBaseFig());
  394. VpToString(vp, psz+strlen(psz), 0, 0);
  395. rb_str_resize(dump, strlen(psz));
  396. return dump;
  397. }
  398. /*
  399. * Internal method used to provide marshalling support. See the Marshal module.
  400. */
  401. static VALUE
  402. BigDecimal_load(VALUE self, VALUE str)
  403. {
  404. ENTER(2);
  405. Real *pv;
  406. unsigned char *pch;
  407. unsigned char ch;
  408. unsigned long m=0;
  409. pch = (unsigned char *)StringValueCStr(str);
  410. /* First get max prec */
  411. while((*pch) != (unsigned char)'\0' && (ch = *pch++) != (unsigned char)':') {
  412. if(!ISDIGIT(ch)) {
  413. rb_raise(rb_eTypeError, "load failed: invalid character in the marshaled string");
  414. }
  415. m = m*10 + (unsigned long)(ch-'0');
  416. }
  417. if (m > VpBaseFig()) m -= VpBaseFig();
  418. GUARD_OBJ(pv, VpNewRbClass(m, (char *)pch, self, true, true));
  419. m /= VpBaseFig();
  420. if (m && pv->MaxPrec > m) {
  421. pv->MaxPrec = m+1;
  422. }
  423. return VpCheckGetValue(pv);
  424. }
  425. static unsigned short
  426. check_rounding_mode_option(VALUE const opts)
  427. {
  428. VALUE mode;
  429. char const *s;
  430. long l;
  431. assert(RB_TYPE_P(opts, T_HASH));
  432. if (NIL_P(opts))
  433. goto noopt;
  434. mode = rb_hash_lookup2(opts, ID2SYM(id_half), Qundef);
  435. if (mode == Qundef || NIL_P(mode))
  436. goto noopt;
  437. if (SYMBOL_P(mode))
  438. mode = rb_sym2str(mode);
  439. else if (!RB_TYPE_P(mode, T_STRING)) {
  440. VALUE str_mode = rb_check_string_type(mode);
  441. if (NIL_P(str_mode)) goto invalid;
  442. mode = str_mode;
  443. }
  444. s = RSTRING_PTR(mode);
  445. l = RSTRING_LEN(mode);
  446. switch (l) {
  447. case 2:
  448. if (strncasecmp(s, "up", 2) == 0)
  449. return VP_ROUND_HALF_UP;
  450. break;
  451. case 4:
  452. if (strncasecmp(s, "even", 4) == 0)
  453. return VP_ROUND_HALF_EVEN;
  454. else if (strncasecmp(s, "down", 4) == 0)
  455. return VP_ROUND_HALF_DOWN;
  456. break;
  457. default:
  458. break;
  459. }
  460. invalid:
  461. if (NIL_P(mode))
  462. rb_raise(rb_eArgError, "invalid rounding mode: nil");
  463. else
  464. rb_raise(rb_eArgError, "invalid rounding mode: %"PRIsVALUE, mode);
  465. noopt:
  466. return VpGetRoundMode();
  467. }
  468. static unsigned short
  469. check_rounding_mode(VALUE const v)
  470. {
  471. unsigned short sw;
  472. ID id;
  473. switch (TYPE(v)) {
  474. case T_SYMBOL:
  475. id = SYM2ID(v);
  476. if (id == id_up)
  477. return VP_ROUND_UP;
  478. if (id == id_down || id == id_truncate)
  479. return VP_ROUND_DOWN;
  480. if (id == id_half_up || id == id_default)
  481. return VP_ROUND_HALF_UP;
  482. if (id == id_half_down)
  483. return VP_ROUND_HALF_DOWN;
  484. if (id == id_half_even || id == id_banker)
  485. return VP_ROUND_HALF_EVEN;
  486. if (id == id_ceiling || id == id_ceil)
  487. return VP_ROUND_CEIL;
  488. if (id == id_floor)
  489. return VP_ROUND_FLOOR;
  490. rb_raise(rb_eArgError, "invalid rounding mode");
  491. default:
  492. break;
  493. }
  494. sw = NUM2USHORT(v);
  495. if (!VpIsRoundMode(sw)) {
  496. rb_raise(rb_eArgError, "invalid rounding mode");
  497. }
  498. return sw;
  499. }
  500. /* call-seq:
  501. * BigDecimal.mode(mode, value)
  502. *
  503. * Controls handling of arithmetic exceptions and rounding. If no value
  504. * is supplied, the current value is returned.
  505. *
  506. * Six values of the mode parameter control the handling of arithmetic
  507. * exceptions:
  508. *
  509. * BigDecimal::EXCEPTION_NaN
  510. * BigDecimal::EXCEPTION_INFINITY
  511. * BigDecimal::EXCEPTION_UNDERFLOW
  512. * BigDecimal::EXCEPTION_OVERFLOW
  513. * BigDecimal::EXCEPTION_ZERODIVIDE
  514. * BigDecimal::EXCEPTION_ALL
  515. *
  516. * For each mode parameter above, if the value set is false, computation
  517. * continues after an arithmetic exception of the appropriate type.
  518. * When computation continues, results are as follows:
  519. *
  520. * EXCEPTION_NaN:: NaN
  521. * EXCEPTION_INFINITY:: +Infinity or -Infinity
  522. * EXCEPTION_UNDERFLOW:: 0
  523. * EXCEPTION_OVERFLOW:: +Infinity or -Infinity
  524. * EXCEPTION_ZERODIVIDE:: +Infinity or -Infinity
  525. *
  526. * One value of the mode parameter controls the rounding of numeric values:
  527. * BigDecimal::ROUND_MODE. The values it can take are:
  528. *
  529. * ROUND_UP, :up:: round away from zero
  530. * ROUND_DOWN, :down, :truncate:: round towards zero (truncate)
  531. * ROUND_HALF_UP, :half_up, :default:: round towards the nearest neighbor, unless both neighbors are equidistant, in which case round away from zero. (default)
  532. * ROUND_HALF_DOWN, :half_down:: round towards the nearest neighbor, unless both neighbors are equidistant, in which case round towards zero.
  533. * 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)
  534. * ROUND_CEILING, :ceiling, :ceil:: round towards positive infinity (ceil)
  535. * ROUND_FLOOR, :floor:: round towards negative infinity (floor)
  536. *
  537. */
  538. static VALUE
  539. BigDecimal_mode(int argc, VALUE *argv, VALUE self)
  540. {
  541. VALUE which;
  542. VALUE val;
  543. unsigned long f,fo;
  544. rb_scan_args(argc, argv, "11", &which, &val);
  545. f = (unsigned long)NUM2INT(which);
  546. if (f & VP_EXCEPTION_ALL) {
  547. /* Exception mode setting */
  548. fo = VpGetException();
  549. if (val == Qnil) return INT2FIX(fo);
  550. if (val != Qfalse && val!=Qtrue) {
  551. rb_raise(rb_eArgError, "second argument must be true or false");
  552. return Qnil; /* Not reached */
  553. }
  554. if (f & VP_EXCEPTION_INFINITY) {
  555. VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_INFINITY) :
  556. (fo & (~VP_EXCEPTION_INFINITY))));
  557. }
  558. fo = VpGetException();
  559. if (f & VP_EXCEPTION_NaN) {
  560. VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_NaN) :
  561. (fo & (~VP_EXCEPTION_NaN))));
  562. }
  563. fo = VpGetException();
  564. if (f & VP_EXCEPTION_UNDERFLOW) {
  565. VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_UNDERFLOW) :
  566. (fo & (~VP_EXCEPTION_UNDERFLOW))));
  567. }
  568. fo = VpGetException();
  569. if(f & VP_EXCEPTION_ZERODIVIDE) {
  570. VpSetException((unsigned short)((val == Qtrue) ? (fo | VP_EXCEPTION_ZERODIVIDE) :
  571. (fo & (~VP_EXCEPTION_ZERODIVIDE))));
  572. }
  573. fo = VpGetException();
  574. return INT2FIX(fo);
  575. }
  576. if (VP_ROUND_MODE == f) {
  577. /* Rounding mode setting */
  578. unsigned short sw;
  579. fo = VpGetRoundMode();
  580. if (NIL_P(val)) return INT2FIX(fo);
  581. sw = check_rounding_mode(val);
  582. fo = VpSetRoundMode(sw);
  583. return INT2FIX(fo);
  584. }
  585. rb_raise(rb_eTypeError, "first argument for BigDecimal.mode invalid");
  586. return Qnil;
  587. }
  588. static size_t
  589. GetAddSubPrec(Real *a, Real *b)
  590. {
  591. size_t mxs;
  592. size_t mx = a->Prec;
  593. SIGNED_VALUE d;
  594. if (!VpIsDef(a) || !VpIsDef(b)) return (size_t)-1L;
  595. if (mx < b->Prec) mx = b->Prec;
  596. if (a->exponent != b->exponent) {
  597. mxs = mx;
  598. d = a->exponent - b->exponent;
  599. if (d < 0) d = -d;
  600. mx = mx + (size_t)d;
  601. if (mx < mxs) {
  602. return VpException(VP_EXCEPTION_INFINITY, "Exponent overflow", 0);
  603. }
  604. }
  605. return mx;
  606. }
  607. static SIGNED_VALUE
  608. GetPrecisionInt(VALUE v)
  609. {
  610. SIGNED_VALUE n;
  611. n = NUM2INT(v);
  612. if (n < 0) {
  613. rb_raise(rb_eArgError, "negative precision");
  614. }
  615. return n;
  616. }
  617. static VALUE
  618. BigDecimal_wrap_struct(VALUE obj, Real *vp)
  619. {
  620. assert(is_kind_of_BigDecimal(obj));
  621. assert(vp != NULL);
  622. if (vp->obj == obj && RTYPEDDATA_DATA(obj) == vp)
  623. return obj;
  624. assert(RTYPEDDATA_DATA(obj) == NULL);
  625. assert(vp->obj == 0);
  626. RTYPEDDATA_DATA(obj) = vp;
  627. vp->obj = obj;
  628. RB_OBJ_FREEZE(obj);
  629. return obj;
  630. }
  631. VP_EXPORT Real *
  632. VpNewRbClass(size_t mx, const char *str, VALUE klass, bool strict_p, bool raise_exception)
  633. {
  634. VALUE obj = TypedData_Wrap_Struct(klass, &BigDecimal_data_type, 0);
  635. Real *pv = VpAlloc(mx, str, strict_p, raise_exception);
  636. if (!pv)
  637. return NULL;
  638. BigDecimal_wrap_struct(obj, pv);
  639. return pv;
  640. }
  641. VP_EXPORT Real *
  642. VpCreateRbObject(size_t mx, const char *str, bool raise_exception)
  643. {
  644. return VpNewRbClass(mx, str, rb_cBigDecimal, true, raise_exception);
  645. }
  646. #define VpAllocReal(prec) (Real *)VpMemAlloc(offsetof(Real, frac) + (prec) * sizeof(DECDIG))
  647. #define VpReallocReal(ptr, prec) (Real *)VpMemRealloc((ptr), offsetof(Real, frac) + (prec) * sizeof(DECDIG))
  648. static Real *
  649. VpCopy(Real *pv, Real const* const x)
  650. {
  651. assert(x != NULL);
  652. pv = VpReallocReal(pv, x->MaxPrec);
  653. pv->MaxPrec = x->MaxPrec;
  654. pv->Prec = x->Prec;
  655. pv->exponent = x->exponent;
  656. pv->sign = x->sign;
  657. pv->flag = x->flag;
  658. MEMCPY(pv->frac, x->frac, DECDIG, pv->MaxPrec);
  659. return pv;
  660. }
  661. /* Returns True if the value is Not a Number. */
  662. static VALUE
  663. BigDecimal_IsNaN(VALUE self)
  664. {
  665. Real *p = GetVpValue(self, 1);
  666. if (VpIsNaN(p)) return Qtrue;
  667. return Qfalse;
  668. }
  669. /* Returns nil, -1, or +1 depending on whether the value is finite,
  670. * -Infinity, or +Infinity.
  671. */
  672. static VALUE
  673. BigDecimal_IsInfinite(VALUE self)
  674. {
  675. Real *p = GetVpValue(self, 1);
  676. if (VpIsPosInf(p)) return INT2FIX(1);
  677. if (VpIsNegInf(p)) return INT2FIX(-1);
  678. return Qnil;
  679. }
  680. /* Returns True if the value is finite (not NaN or infinite). */
  681. static VALUE
  682. BigDecimal_IsFinite(VALUE self)
  683. {
  684. Real *p = GetVpValue(self, 1);
  685. if (VpIsNaN(p)) return Qfalse;
  686. if (VpIsInf(p)) return Qfalse;
  687. return Qtrue;
  688. }
  689. static void
  690. BigDecimal_check_num(Real *p)
  691. {
  692. VpCheckException(p, true);
  693. }
  694. static VALUE BigDecimal_split(VALUE self);
  695. /* Returns the value as an Integer.
  696. *
  697. * If the BigDecimal is infinity or NaN, raises FloatDomainError.
  698. */
  699. static VALUE
  700. BigDecimal_to_i(VALUE self)
  701. {
  702. ENTER(5);
  703. ssize_t e, nf;
  704. Real *p;
  705. GUARD_OBJ(p, GetVpValue(self, 1));
  706. BigDecimal_check_num(p);
  707. e = VpExponent10(p);
  708. if (e <= 0) return INT2FIX(0);
  709. nf = VpBaseFig();
  710. if (e <= nf) {
  711. return LONG2NUM((long)(VpGetSign(p) * (DECDIG_DBL_SIGNED)p->frac[0]));
  712. }
  713. else {
  714. VALUE a = BigDecimal_split(self);
  715. VALUE digits = RARRAY_AREF(a, 1);
  716. VALUE numerator = rb_funcall(digits, rb_intern("to_i"), 0);
  717. VALUE ret;
  718. ssize_t dpower = e - (ssize_t)RSTRING_LEN(digits);
  719. if (BIGDECIMAL_NEGATIVE_P(p)) {
  720. numerator = rb_funcall(numerator, '*', 1, INT2FIX(-1));
  721. }
  722. if (dpower < 0) {
  723. ret = rb_funcall(numerator, rb_intern("div"), 1,
  724. rb_funcall(INT2FIX(10), rb_intern("**"), 1,
  725. INT2FIX(-dpower)));
  726. }
  727. else {
  728. ret = rb_funcall(numerator, '*', 1,
  729. rb_funcall(INT2FIX(10), rb_intern("**"), 1,
  730. INT2FIX(dpower)));
  731. }
  732. if (RB_TYPE_P(ret, T_FLOAT)) {
  733. rb_raise(rb_eFloatDomainError, "Infinity");
  734. }
  735. return ret;
  736. }
  737. }
  738. /* Returns a new Float object having approximately the same value as the
  739. * BigDecimal number. Normal accuracy limits and built-in errors of binary
  740. * Float arithmetic apply.
  741. */
  742. static VALUE
  743. BigDecimal_to_f(VALUE self)
  744. {
  745. ENTER(1);
  746. Real *p;
  747. double d;
  748. SIGNED_VALUE e;
  749. char *buf;
  750. volatile VALUE str;
  751. GUARD_OBJ(p, GetVpValue(self, 1));
  752. if (VpVtoD(&d, &e, p) != 1)
  753. return rb_float_new(d);
  754. if (e > (SIGNED_VALUE)(DBL_MAX_10_EXP+BASE_FIG))
  755. goto overflow;
  756. if (e < (SIGNED_VALUE)(DBL_MIN_10_EXP-BASE_FIG))
  757. goto underflow;
  758. str = rb_str_new(0, VpNumOfChars(p, "E"));
  759. buf = RSTRING_PTR(str);
  760. VpToString(p, buf, 0, 0);
  761. errno = 0;
  762. d = strtod(buf, 0);
  763. if (errno == ERANGE) {
  764. if (d == 0.0) goto underflow;
  765. if (fabs(d) >= HUGE_VAL) goto overflow;
  766. }
  767. return rb_float_new(d);
  768. overflow:
  769. VpException(VP_EXCEPTION_OVERFLOW, "BigDecimal to Float conversion", 0);
  770. if (BIGDECIMAL_NEGATIVE_P(p))
  771. return rb_float_new(VpGetDoubleNegInf());
  772. else
  773. return rb_float_new(VpGetDoublePosInf());
  774. underflow:
  775. VpException(VP_EXCEPTION_UNDERFLOW, "BigDecimal to Float conversion", 0);
  776. if (BIGDECIMAL_NEGATIVE_P(p))
  777. return rb_float_new(-0.0);
  778. else
  779. return rb_float_new(0.0);
  780. }
  781. /* Converts a BigDecimal to a Rational.
  782. */
  783. static VALUE
  784. BigDecimal_to_r(VALUE self)
  785. {
  786. Real *p;
  787. ssize_t sign, power, denomi_power;
  788. VALUE a, digits, numerator;
  789. p = GetVpValue(self, 1);
  790. BigDecimal_check_num(p);
  791. sign = VpGetSign(p);
  792. power = VpExponent10(p);
  793. a = BigDecimal_split(self);
  794. digits = RARRAY_AREF(a, 1);
  795. denomi_power = power - RSTRING_LEN(digits);
  796. numerator = rb_funcall(digits, rb_intern("to_i"), 0);
  797. if (sign < 0) {
  798. numerator = rb_funcall(numerator, '*', 1, INT2FIX(-1));
  799. }
  800. if (denomi_power < 0) {
  801. return rb_Rational(numerator,
  802. rb_funcall(INT2FIX(10), rb_intern("**"), 1,
  803. INT2FIX(-denomi_power)));
  804. }
  805. else {
  806. return rb_Rational1(rb_funcall(numerator, '*', 1,
  807. rb_funcall(INT2FIX(10), rb_intern("**"), 1,
  808. INT2FIX(denomi_power))));
  809. }
  810. }
  811. /* The coerce method provides support for Ruby type coercion. It is not
  812. * enabled by default.
  813. *
  814. * This means that binary operations like + * / or - can often be performed
  815. * on a BigDecimal and an object of another type, if the other object can
  816. * be coerced into a BigDecimal value.
  817. *
  818. * e.g.
  819. * a = BigDecimal("1.0")
  820. * b = a / 2.0 #=> 0.5
  821. *
  822. * Note that coercing a String to a BigDecimal is not supported by default;
  823. * it requires a special compile-time option when building Ruby.
  824. */
  825. static VALUE
  826. BigDecimal_coerce(VALUE self, VALUE other)
  827. {
  828. ENTER(2);
  829. VALUE obj;
  830. Real *b;
  831. if (RB_TYPE_P(other, T_FLOAT)) {
  832. GUARD_OBJ(b, GetVpValueWithPrec(other, 0, 1));
  833. obj = rb_assoc_new(VpCheckGetValue(b), self);
  834. }
  835. else {
  836. if (RB_TYPE_P(other, T_RATIONAL)) {
  837. Real* pv = DATA_PTR(self);
  838. GUARD_OBJ(b, GetVpValueWithPrec(other, pv->Prec*VpBaseFig(), 1));
  839. }
  840. else {
  841. GUARD_OBJ(b, GetVpValue(other, 1));
  842. }
  843. obj = rb_assoc_new(b->obj, self);
  844. }
  845. return obj;
  846. }
  847. /*
  848. * call-seq:
  849. * +big_decimal -> big_decimal
  850. *
  851. * Return self.
  852. *
  853. * +BigDecimal('5') #=> 0.5e1
  854. */
  855. static VALUE
  856. BigDecimal_uplus(VALUE self)
  857. {
  858. return self;
  859. }
  860. /*
  861. * Document-method: BigDecimal#add
  862. * Document-method: BigDecimal#+
  863. *
  864. * call-seq:
  865. * add(value, digits)
  866. *
  867. * Add the specified value.
  868. *
  869. * e.g.
  870. * c = a.add(b,n)
  871. * c = a + b
  872. *
  873. * digits:: If specified and less than the number of significant digits of the
  874. * result, the result is rounded to that number of digits, according
  875. * to BigDecimal.mode.
  876. */
  877. static VALUE
  878. BigDecimal_add(VALUE self, VALUE r)
  879. {
  880. ENTER(5);
  881. Real *c, *a, *b;
  882. size_t mx;
  883. GUARD_OBJ(a, GetVpValue(self, 1));
  884. if (RB_TYPE_P(r, T_FLOAT)) {
  885. b = GetVpValueWithPrec(r, 0, 1);
  886. }
  887. else if (RB_TYPE_P(r, T_RATIONAL)) {
  888. b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
  889. }
  890. else {
  891. b = GetVpValue(r, 0);
  892. }
  893. if (!b) return DoSomeOne(self,r,'+');
  894. SAVE(b);
  895. if (VpIsNaN(b)) return b->obj;
  896. if (VpIsNaN(a)) return a->obj;
  897. mx = GetAddSubPrec(a, b);
  898. if (mx == (size_t)-1L) {
  899. GUARD_OBJ(c, VpCreateRbObject(VpBaseFig() + 1, "0", true));
  900. VpAddSub(c, a, b, 1);
  901. }
  902. else {
  903. GUARD_OBJ(c, VpCreateRbObject(mx * (VpBaseFig() + 1), "0", true));
  904. if(!mx) {
  905. VpSetInf(c, VpGetSign(a));
  906. }
  907. else {
  908. VpAddSub(c, a, b, 1);
  909. }
  910. }
  911. return VpCheckGetValue(c);
  912. }
  913. /* call-seq:
  914. * a - b -> bigdecimal
  915. *
  916. * Subtract the specified value.
  917. *
  918. * e.g.
  919. * c = a - b
  920. *
  921. * The precision of the result value depends on the type of +b+.
  922. *
  923. * If +b+ is a Float, the precision of the result is Float::DIG+1.
  924. *
  925. * If +b+ is a BigDecimal, the precision of the result is +b+'s precision of
  926. * internal representation from platform. So, it's return value is platform
  927. * dependent.
  928. *
  929. */
  930. static VALUE
  931. BigDecimal_sub(VALUE self, VALUE r)
  932. {
  933. ENTER(5);
  934. Real *c, *a, *b;
  935. size_t mx;
  936. GUARD_OBJ(a, GetVpValue(self,1));
  937. if (RB_TYPE_P(r, T_FLOAT)) {
  938. b = GetVpValueWithPrec(r, 0, 1);
  939. }
  940. else if (RB_TYPE_P(r, T_RATIONAL)) {
  941. b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
  942. }
  943. else {
  944. b = GetVpValue(r,0);
  945. }
  946. if (!b) return DoSomeOne(self,r,'-');
  947. SAVE(b);
  948. if (VpIsNaN(b)) return b->obj;
  949. if (VpIsNaN(a)) return a->obj;
  950. mx = GetAddSubPrec(a,b);
  951. if (mx == (size_t)-1L) {
  952. GUARD_OBJ(c, VpCreateRbObject(VpBaseFig() + 1, "0", true));
  953. VpAddSub(c, a, b, -1);
  954. }
  955. else {
  956. GUARD_OBJ(c,VpCreateRbObject(mx *(VpBaseFig() + 1), "0", true));
  957. if (!mx) {
  958. VpSetInf(c,VpGetSign(a));
  959. }
  960. else {
  961. VpAddSub(c, a, b, -1);
  962. }
  963. }
  964. return VpCheckGetValue(c);
  965. }
  966. static VALUE
  967. BigDecimalCmp(VALUE self, VALUE r,char op)
  968. {
  969. ENTER(5);
  970. SIGNED_VALUE e;
  971. Real *a, *b=0;
  972. GUARD_OBJ(a, GetVpValue(self, 1));
  973. switch (TYPE(r)) {
  974. case T_DATA:
  975. if (!is_kind_of_BigDecimal(r)) break;
  976. /* fall through */
  977. case T_FIXNUM:
  978. /* fall through */
  979. case T_BIGNUM:
  980. GUARD_OBJ(b, GetVpValue(r, 0));
  981. break;
  982. case T_FLOAT:
  983. GUARD_OBJ(b, GetVpValueWithPrec(r, 0, 0));
  984. break;
  985. case T_RATIONAL:
  986. GUARD_OBJ(b, GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 0));
  987. break;
  988. default:
  989. break;
  990. }
  991. if (b == NULL) {
  992. ID f = 0;
  993. switch (op) {
  994. case '*':
  995. return rb_num_coerce_cmp(self, r, rb_intern("<=>"));
  996. case '=':
  997. return RTEST(rb_num_coerce_cmp(self, r, rb_intern("=="))) ? Qtrue : Qfalse;
  998. case 'G':
  999. f = rb_intern(">=");
  1000. break;
  1001. case 'L':
  1002. f = rb_intern("<=");
  1003. break;
  1004. case '>':
  1005. /* fall through */
  1006. case '<':
  1007. f = (ID)op;
  1008. break;
  1009. default:
  1010. break;
  1011. }
  1012. return rb_num_coerce_relop(self, r, f);
  1013. }
  1014. SAVE(b);
  1015. e = VpComp(a, b);
  1016. if (e == 999)
  1017. return (op == '*') ? Qnil : Qfalse;
  1018. switch (op) {
  1019. case '*':
  1020. return INT2FIX(e); /* any op */
  1021. case '=':
  1022. if (e == 0) return Qtrue;
  1023. return Qfalse;
  1024. case 'G':
  1025. if (e >= 0) return Qtrue;
  1026. return Qfalse;
  1027. case '>':
  1028. if (e > 0) return Qtrue;
  1029. return Qfalse;
  1030. case 'L':
  1031. if (e <= 0) return Qtrue;
  1032. return Qfalse;
  1033. case '<':
  1034. if (e < 0) return Qtrue;
  1035. return Qfalse;
  1036. default:
  1037. break;
  1038. }
  1039. rb_bug("Undefined operation in BigDecimalCmp()");
  1040. UNREACHABLE;
  1041. }
  1042. /* Returns True if the value is zero. */
  1043. static VALUE
  1044. BigDecimal_zero(VALUE self)
  1045. {
  1046. Real *a = GetVpValue(self, 1);
  1047. return VpIsZero(a) ? Qtrue : Qfalse;
  1048. }
  1049. /* Returns self if the value is non-zero, nil otherwise. */
  1050. static VALUE
  1051. BigDecimal_nonzero(VALUE self)
  1052. {
  1053. Real *a = GetVpValue(self, 1);
  1054. return VpIsZero(a) ? Qnil : self;
  1055. }
  1056. /* The comparison operator.
  1057. * a <=> b is 0 if a == b, 1 if a > b, -1 if a < b.
  1058. */
  1059. static VALUE
  1060. BigDecimal_comp(VALUE self, VALUE r)
  1061. {
  1062. return BigDecimalCmp(self, r, '*');
  1063. }
  1064. /*
  1065. * Tests for value equality; returns true if the values are equal.
  1066. *
  1067. * The == and === operators and the eql? method have the same implementation
  1068. * for BigDecimal.
  1069. *
  1070. * Values may be coerced to perform the comparison:
  1071. *
  1072. * BigDecimal('1.0') == 1.0 #=> true
  1073. */
  1074. static VALUE
  1075. BigDecimal_eq(VALUE self, VALUE r)
  1076. {
  1077. return BigDecimalCmp(self, r, '=');
  1078. }
  1079. /* call-seq:
  1080. * a < b
  1081. *
  1082. * Returns true if a is less than b.
  1083. *
  1084. * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce).
  1085. */
  1086. static VALUE
  1087. BigDecimal_lt(VALUE self, VALUE r)
  1088. {
  1089. return BigDecimalCmp(self, r, '<');
  1090. }
  1091. /* call-seq:
  1092. * a <= b
  1093. *
  1094. * Returns true if a is less than or equal to b.
  1095. *
  1096. * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce).
  1097. */
  1098. static VALUE
  1099. BigDecimal_le(VALUE self, VALUE r)
  1100. {
  1101. return BigDecimalCmp(self, r, 'L');
  1102. }
  1103. /* call-seq:
  1104. * a > b
  1105. *
  1106. * Returns true if a is greater than b.
  1107. *
  1108. * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce).
  1109. */
  1110. static VALUE
  1111. BigDecimal_gt(VALUE self, VALUE r)
  1112. {
  1113. return BigDecimalCmp(self, r, '>');
  1114. }
  1115. /* call-seq:
  1116. * a >= b
  1117. *
  1118. * Returns true if a is greater than or equal to b.
  1119. *
  1120. * Values may be coerced to perform the comparison (see ==, BigDecimal#coerce)
  1121. */
  1122. static VALUE
  1123. BigDecimal_ge(VALUE self, VALUE r)
  1124. {
  1125. return BigDecimalCmp(self, r, 'G');
  1126. }
  1127. /*
  1128. * call-seq:
  1129. * -big_decimal -> big_decimal
  1130. *
  1131. * Return the negation of self.
  1132. *
  1133. * -BigDecimal('5') #=> -0.5e1
  1134. */
  1135. static VALUE
  1136. BigDecimal_neg(VALUE self)
  1137. {
  1138. ENTER(5);
  1139. Real *c, *a;
  1140. GUARD_OBJ(a, GetVpValue(self, 1));
  1141. GUARD_OBJ(c, VpCreateRbObject(a->Prec *(VpBaseFig() + 1), "0", true));
  1142. VpAsgn(c, a, -1);
  1143. return VpCheckGetValue(c);
  1144. }
  1145. /*
  1146. * Document-method: BigDecimal#mult
  1147. *
  1148. * call-seq: mult(value, digits)
  1149. *
  1150. * Multiply by the specified value.
  1151. *
  1152. * e.g.
  1153. * c = a.mult(b,n)
  1154. * c = a * b
  1155. *
  1156. * digits:: If specified and less than the number of significant digits of the
  1157. * result, the result is rounded to that number of digits, according
  1158. * to BigDecimal.mode.
  1159. */
  1160. static VALUE
  1161. BigDecimal_mult(VALUE self, VALUE r)
  1162. {
  1163. ENTER(5);
  1164. Real *c, *a, *b;
  1165. size_t mx;
  1166. GUARD_OBJ(a, GetVpValue(self, 1));
  1167. if (RB_TYPE_P(r, T_FLOAT)) {
  1168. b = GetVpValueWithPrec(r, 0, 1);
  1169. }
  1170. else if (RB_TYPE_P(r, T_RATIONAL)) {
  1171. b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
  1172. }
  1173. else {
  1174. b = GetVpValue(r,0);
  1175. }
  1176. if (!b) return DoSomeOne(self, r, '*');
  1177. SAVE(b);
  1178. mx = a->Prec + b->Prec;
  1179. GUARD_OBJ(c, VpCreateRbObject(mx *(VpBaseFig() + 1), "0", true));
  1180. VpMult(c, a, b);
  1181. return VpCheckGetValue(c);
  1182. }
  1183. static VALUE
  1184. BigDecimal_divide(VALUE self, VALUE r, Real **c, Real **res, Real **div)
  1185. /* For c = self.div(r): with round operation */
  1186. {
  1187. ENTER(5);
  1188. Real *a, *b;
  1189. size_t mx;
  1190. TypedData_Get_Struct(self, Real, &BigDecimal_data_type, a);
  1191. SAVE(a);
  1192. VALUE rr = r;
  1193. if (is_kind_of_BigDecimal(rr)) {
  1194. /* do nothing */
  1195. }
  1196. else if (RB_INTEGER_TYPE_P(r)) {
  1197. rr = rb_inum_convert_to_BigDecimal(r, 0, true);
  1198. }
  1199. else if (RB_TYPE_P(r, T_FLOAT)) {
  1200. rr = rb_float_convert_to_BigDecimal(r, 0, true);
  1201. }
  1202. else if (RB_TYPE_P(r, T_RATIONAL)) {
  1203. rr = rb_rational_convert_to_BigDecimal(r, a->Prec*BASE_FIG, true);
  1204. }
  1205. if (!is_kind_of_BigDecimal(rr)) {
  1206. return DoSomeOne(self, r, '/');
  1207. }
  1208. TypedData_Get_Struct(rr, Real, &BigDecimal_data_type, b);
  1209. SAVE(b);
  1210. *div = b;
  1211. mx = a->Prec + vabs(a->exponent);
  1212. if (mx < b->Prec + vabs(b->exponent)) mx = b->Prec + vabs(b->exponent);
  1213. mx++; /* NOTE: An additional digit is needed for the compatibility to
  1214. the version 1.2.1 and the former. */
  1215. mx = (mx + 1) * VpBaseFig();
  1216. GUARD_OBJ((*c), VpCreateRbObject(mx, "#0", true));
  1217. GUARD_OBJ((*res), VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0", true));
  1218. VpDivd(*c, *res, a, b);
  1219. return Qnil;
  1220. }
  1221. /* call-seq:
  1222. * a / b -> bigdecimal
  1223. * quo(value) -> bigdecimal
  1224. *
  1225. * Divide by the specified value.
  1226. *
  1227. * See BigDecimal#div.
  1228. */
  1229. static VALUE
  1230. BigDecimal_div(VALUE self, VALUE r)
  1231. /* For c = self/r: with round operation */
  1232. {
  1233. ENTER(5);
  1234. Real *c=NULL, *res=NULL, *div = NULL;
  1235. r = BigDecimal_divide(self, r, &c, &res, &div);
  1236. if (!NIL_P(r)) return r; /* coerced by other */
  1237. SAVE(c); SAVE(res); SAVE(div);
  1238. /* a/b = c + r/b */
  1239. /* c xxxxx
  1240. r 00000yyyyy ==> (y/b)*BASE >= HALF_BASE
  1241. */
  1242. /* Round */
  1243. if (VpHasVal(div)) { /* frac[0] must be zero for NaN,INF,Zero */
  1244. VpInternalRound(c, 0, c->frac[c->Prec-1], (DECDIG)(VpBaseVal() * (DECDIG_DBL)res->frac[0] / div->frac[0]));
  1245. }
  1246. return VpCheckGetValue(c);
  1247. }
  1248. /*
  1249. * %: mod = a%b = a - (a.to_f/b).floor * b
  1250. * div = (a.to_f/b).floor
  1251. */
  1252. static VALUE
  1253. BigDecimal_DoDivmod(VALUE self, VALUE r, Real **div, Real **mod)
  1254. {
  1255. ENTER(8);
  1256. Real *c=NULL, *d=NULL, *res=NULL;
  1257. Real *a, *b;
  1258. size_t mx;
  1259. TypedData_Get_Struct(self, Real, &BigDecimal_data_type, a);
  1260. SAVE(a);
  1261. VALUE rr = r;
  1262. if (is_kind_of_BigDecimal(rr)) {
  1263. /* do nothing */
  1264. }
  1265. else if (RB_INTEGER_TYPE_P(r)) {
  1266. rr = rb_inum_convert_to_BigDecimal(r, 0, true);
  1267. }
  1268. else if (RB_TYPE_P(r, T_FLOAT)) {
  1269. rr = rb_float_convert_to_BigDecimal(r, 0, true);
  1270. }
  1271. else if (RB_TYPE_P(r, T_RATIONAL)) {
  1272. rr = rb_rational_convert_to_BigDecimal(r, a->Prec*BASE_FIG, true);
  1273. }
  1274. if (!is_kind_of_BigDecimal(rr)) {
  1275. return Qfalse;
  1276. }
  1277. TypedData_Get_Struct(rr, Real, &BigDecimal_data_type, b);
  1278. SAVE(b);
  1279. if (VpIsNaN(a) || VpIsNaN(b)) goto NaN;
  1280. if (VpIsInf(a) && VpIsInf(b)) goto NaN;
  1281. if (VpIsZero(b)) {
  1282. rb_raise(rb_eZeroDivError, "divided by 0");
  1283. }
  1284. if (VpIsInf(a)) {
  1285. if (VpGetSign(a) == VpGetSign(b)) {
  1286. VALUE inf = BigDecimal_positive_infinity();
  1287. TypedData_Get_Struct(inf, Real, &BigDecimal_data_type, *div);
  1288. }
  1289. else {
  1290. VALUE inf = BigDecimal_negative_infinity();
  1291. TypedData_Get_Struct(inf, Real, &BigDecimal_data_type, *div);
  1292. }
  1293. VALUE nan = BigDecimal_nan();
  1294. TypedData_Get_Struct(nan, Real, &BigDecimal_data_type, *mod);
  1295. return Qtrue;
  1296. }
  1297. if (VpIsInf(b)) {
  1298. VALUE zero = BigDecimal_positive_zero();
  1299. TypedData_Get_Struct(zero, Real, &BigDecimal_data_type, *div);
  1300. *mod = a;
  1301. return Qtrue;
  1302. }
  1303. if (VpIsZero(a)) {
  1304. VALUE zero = BigDecimal_positive_zero();
  1305. TypedData_Get_Struct(zero, Real, &BigDecimal_data_type, *div);
  1306. TypedData_Get_Struct(zero, Real, &BigDecimal_data_type, *mod);
  1307. return Qtrue;
  1308. }
  1309. mx = a->Prec + vabs(a->exponent);
  1310. if (mx<b->Prec + vabs(b->exponent)) mx = b->Prec + vabs(b->exponent);
  1311. mx = (mx + 1) * VpBaseFig();
  1312. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1313. GUARD_OBJ(res, VpCreateRbObject((mx+1) * 2 +(VpBaseFig() + 1), "#0", true));
  1314. VpDivd(c, res, a, b);
  1315. mx = c->Prec * (VpBaseFig() + 1);
  1316. GUARD_OBJ(d, VpCreateRbObject(mx, "0", true));
  1317. VpActiveRound(d, c, VP_ROUND_DOWN, 0);
  1318. VpMult(res, d, b);
  1319. VpAddSub(c, a, res, -1);
  1320. if (!VpIsZero(c) && (VpGetSign(a) * VpGetSign(b) < 0)) {
  1321. VpAddSub(res, d, VpOne(), -1);
  1322. GUARD_OBJ(d, VpCreateRbObject(GetAddSubPrec(c, b)*(VpBaseFig() + 1), "0", true));
  1323. VpAddSub(d, c, b, 1);
  1324. *div = res;
  1325. *mod = d;
  1326. } else {
  1327. *div = d;
  1328. *mod = c;
  1329. }
  1330. return Qtrue;
  1331. NaN:
  1332. {
  1333. VALUE nan = BigDecimal_nan();
  1334. TypedData_Get_Struct(nan, Real, &BigDecimal_data_type, *div);
  1335. TypedData_Get_Struct(nan, Real, &BigDecimal_data_type, *mod);
  1336. }
  1337. return Qtrue;
  1338. }
  1339. /* call-seq:
  1340. * a % b
  1341. * a.modulo(b)
  1342. *
  1343. * Returns the modulus from dividing by b.
  1344. *
  1345. * See BigDecimal#divmod.
  1346. */
  1347. static VALUE
  1348. BigDecimal_mod(VALUE self, VALUE r) /* %: a%b = a - (a.to_f/b).floor * b */
  1349. {
  1350. ENTER(3);
  1351. Real *div = NULL, *mod = NULL;
  1352. if (BigDecimal_DoDivmod(self, r, &div, &mod)) {
  1353. SAVE(div); SAVE(mod);
  1354. return VpCheckGetValue(mod);
  1355. }
  1356. return DoSomeOne(self, r, '%');
  1357. }
  1358. static VALUE
  1359. BigDecimal_divremain(VALUE self, VALUE r, Real **dv, Real **rv)
  1360. {
  1361. ENTER(10);
  1362. size_t mx;
  1363. Real *a = NULL, *b = NULL, *c = NULL, *res = NULL, *d = NULL, *rr = NULL, *ff = NULL;
  1364. Real *f = NULL;
  1365. GUARD_OBJ(a, GetVpValue(self, 1));
  1366. if (RB_TYPE_P(r, T_FLOAT)) {
  1367. b = GetVpValueWithPrec(r, 0, 1);
  1368. }
  1369. else if (RB_TYPE_P(r, T_RATIONAL)) {
  1370. b = GetVpValueWithPrec(r, a->Prec*VpBaseFig(), 1);
  1371. }
  1372. else {
  1373. b = GetVpValue(r, 0);
  1374. }
  1375. if (!b) return DoSomeOne(self, r, rb_intern("remainder"));
  1376. SAVE(b);
  1377. mx = (a->MaxPrec + b->MaxPrec) *VpBaseFig();
  1378. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1379. GUARD_OBJ(res, VpCreateRbObject((mx+1) * 2 + (VpBaseFig() + 1), "#0", true));
  1380. GUARD_OBJ(rr, VpCreateRbObject((mx+1) * 2 + (VpBaseFig() + 1), "#0", true));
  1381. GUARD_OBJ(ff, VpCreateRbObject((mx+1) * 2 + (VpBaseFig() + 1), "#0", true));
  1382. VpDivd(c, res, a, b);
  1383. mx = c->Prec *(VpBaseFig() + 1);
  1384. GUARD_OBJ(d, VpCreateRbObject(mx, "0", true));
  1385. GUARD_OBJ(f, VpCreateRbObject(mx, "0", true));
  1386. VpActiveRound(d, c, VP_ROUND_DOWN, 0); /* 0: round off */
  1387. VpFrac(f, c);
  1388. VpMult(rr, f, b);
  1389. VpAddSub(ff, res, rr, 1);
  1390. *dv = d;
  1391. *rv = ff;
  1392. return Qnil;
  1393. }
  1394. /* call-seq:
  1395. * remainder(value)
  1396. *
  1397. * Returns the remainder from dividing by the value.
  1398. *
  1399. * x.remainder(y) means x-y*(x/y).truncate
  1400. */
  1401. static VALUE
  1402. BigDecimal_remainder(VALUE self, VALUE r) /* remainder */
  1403. {
  1404. VALUE f;
  1405. Real *d, *rv = 0;
  1406. f = BigDecimal_divremain(self, r, &d, &rv);
  1407. if (!NIL_P(f)) return f;
  1408. return VpCheckGetValue(rv);
  1409. }
  1410. /* call-seq:
  1411. * divmod(value)
  1412. *
  1413. * Divides by the specified value, and returns the quotient and modulus
  1414. * as BigDecimal numbers. The quotient is rounded towards negative infinity.
  1415. *
  1416. * For example:
  1417. *
  1418. * require 'bigdecimal'
  1419. *
  1420. * a = BigDecimal("42")
  1421. * b = BigDecimal("9")
  1422. *
  1423. * q, m = a.divmod(b)
  1424. *
  1425. * c = q * b + m
  1426. *
  1427. * a == c #=> true
  1428. *
  1429. * The quotient q is (a/b).floor, and the modulus is the amount that must be
  1430. * added to q * b to get a.
  1431. */
  1432. static VALUE
  1433. BigDecimal_divmod(VALUE self, VALUE r)
  1434. {
  1435. ENTER(5);
  1436. Real *div = NULL, *mod = NULL;
  1437. if (BigDecimal_DoDivmod(self, r, &div, &mod)) {
  1438. SAVE(div); SAVE(mod);
  1439. return rb_assoc_new(VpCheckGetValue(div), VpCheckGetValue(mod));
  1440. }
  1441. return DoSomeOne(self,r,rb_intern("divmod"));
  1442. }
  1443. /*
  1444. * Do the same manner as Float#div when n is nil.
  1445. * Do the same manner as BigDecimal#quo when n is 0.
  1446. */
  1447. static inline VALUE
  1448. BigDecimal_div2(VALUE self, VALUE b, VALUE n)
  1449. {
  1450. ENTER(5);
  1451. SIGNED_VALUE ix;
  1452. if (NIL_P(n)) { /* div in Float sense */
  1453. Real *div = NULL;
  1454. Real *mod;
  1455. if (BigDecimal_DoDivmod(self, b, &div, &mod)) {
  1456. return BigDecimal_to_i(VpCheckGetValue(div));
  1457. }
  1458. return DoSomeOne(self, b, rb_intern("div"));
  1459. }
  1460. /* div in BigDecimal sense */
  1461. ix = GetPrecisionInt(n);
  1462. if (ix == 0) {
  1463. return BigDecimal_div(self, b);
  1464. }
  1465. else {
  1466. Real *res = NULL;
  1467. Real *av = NULL, *bv = NULL, *cv = NULL;
  1468. size_t mx = ix + VpBaseFig()*2;
  1469. size_t pl = VpSetPrecLimit(0);
  1470. GUARD_OBJ(cv, VpCreateRbObject(mx + VpBaseFig(), "0", true));
  1471. GUARD_OBJ(av, GetVpValue(self, 1));
  1472. GUARD_OBJ(bv, GetVpValue(b, 1));
  1473. mx = av->Prec + bv->Prec + 2;
  1474. if (mx <= cv->MaxPrec) mx = cv->MaxPrec + 1;
  1475. GUARD_OBJ(res, VpCreateRbObject((mx * 2 + 2)*VpBaseFig(), "#0", true));
  1476. VpDivd(cv, res, av, bv);
  1477. VpSetPrecLimit(pl);
  1478. VpLeftRound(cv, VpGetRoundMode(), ix);
  1479. return VpCheckGetValue(cv);
  1480. }
  1481. }
  1482. /*
  1483. * Document-method: BigDecimal#div
  1484. *
  1485. * call-seq:
  1486. * div(value, digits) -> bigdecimal or integer
  1487. *
  1488. * Divide by the specified value.
  1489. *
  1490. * digits:: If specified and less than the number of significant digits of the
  1491. * result, the result is rounded to that number of digits, according
  1492. * to BigDecimal.mode.
  1493. *
  1494. * If digits is 0, the result is the same as for the / operator
  1495. * or #quo.
  1496. *
  1497. * If digits is not specified, the result is an integer,
  1498. * by analogy with Float#div; see also BigDecimal#divmod.
  1499. *
  1500. * Examples:
  1501. *
  1502. * a = BigDecimal("4")
  1503. * b = BigDecimal("3")
  1504. *
  1505. * a.div(b, 3) # => 0.133e1
  1506. *
  1507. * a.div(b, 0) # => 0.1333333333333333333e1
  1508. * a / b # => 0.1333333333333333333e1
  1509. * a.quo(b) # => 0.1333333333333333333e1
  1510. *
  1511. * a.div(b) # => 1
  1512. */
  1513. static VALUE
  1514. BigDecimal_div3(int argc, VALUE *argv, VALUE self)
  1515. {
  1516. VALUE b,n;
  1517. rb_scan_args(argc, argv, "11", &b, &n);
  1518. return BigDecimal_div2(self, b, n);
  1519. }
  1520. static VALUE
  1521. BigDecimal_add2(VALUE self, VALUE b, VALUE n)
  1522. {
  1523. ENTER(2);
  1524. Real *cv;
  1525. SIGNED_VALUE mx = GetPrecisionInt(n);
  1526. if (mx == 0) return BigDecimal_add(self, b);
  1527. else {
  1528. size_t pl = VpSetPrecLimit(0);
  1529. VALUE c = BigDecimal_add(self, b);
  1530. VpSetPrecLimit(pl);
  1531. GUARD_OBJ(cv, GetVpValue(c, 1));
  1532. VpLeftRound(cv, VpGetRoundMode(), mx);
  1533. return VpCheckGetValue(cv);
  1534. }
  1535. }
  1536. /* call-seq:
  1537. * sub(value, digits) -> bigdecimal
  1538. *
  1539. * Subtract the specified value.
  1540. *
  1541. * e.g.
  1542. * c = a.sub(b,n)
  1543. *
  1544. * digits:: If specified and less than the number of significant digits of the
  1545. * result, the result is rounded to that number of digits, according
  1546. * to BigDecimal.mode.
  1547. *
  1548. */
  1549. static VALUE
  1550. BigDecimal_sub2(VALUE self, VALUE b, VALUE n)
  1551. {
  1552. ENTER(2);
  1553. Real *cv;
  1554. SIGNED_VALUE mx = GetPrecisionInt(n);
  1555. if (mx == 0) return BigDecimal_sub(self, b);
  1556. else {
  1557. size_t pl = VpSetPrecLimit(0);
  1558. VALUE c = BigDecimal_sub(self, b);
  1559. VpSetPrecLimit(pl);
  1560. GUARD_OBJ(cv, GetVpValue(c, 1));
  1561. VpLeftRound(cv, VpGetRoundMode(), mx);
  1562. return VpCheckGetValue(cv);
  1563. }
  1564. }
  1565. static VALUE
  1566. BigDecimal_mult2(VALUE self, VALUE b, VALUE n)
  1567. {
  1568. ENTER(2);
  1569. Real *cv;
  1570. SIGNED_VALUE mx = GetPrecisionInt(n);
  1571. if (mx == 0) return BigDecimal_mult(self, b);
  1572. else {
  1573. size_t pl = VpSetPrecLimit(0);
  1574. VALUE c = BigDecimal_mult(self, b);
  1575. VpSetPrecLimit(pl);
  1576. GUARD_OBJ(cv, GetVpValue(c, 1));
  1577. VpLeftRound(cv, VpGetRoundMode(), mx);
  1578. return VpCheckGetValue(cv);
  1579. }
  1580. }
  1581. /*
  1582. * call-seq:
  1583. * big_decimal.abs -> big_decimal
  1584. *
  1585. * Returns the absolute value, as a BigDecimal.
  1586. *
  1587. * BigDecimal('5').abs #=> 0.5e1
  1588. * BigDecimal('-3').abs #=> 0.3e1
  1589. */
  1590. static VALUE
  1591. BigDecimal_abs(VALUE self)
  1592. {
  1593. ENTER(5);
  1594. Real *c, *a;
  1595. size_t mx;
  1596. GUARD_OBJ(a, GetVpValue(self, 1));
  1597. mx = a->Prec *(VpBaseFig() + 1);
  1598. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1599. VpAsgn(c, a, 1);
  1600. VpChangeSign(c, 1);
  1601. return VpCheckGetValue(c);
  1602. }
  1603. /* call-seq:
  1604. * sqrt(n)
  1605. *
  1606. * Returns the square root of the value.
  1607. *
  1608. * Result has at least n significant digits.
  1609. */
  1610. static VALUE
  1611. BigDecimal_sqrt(VALUE self, VALUE nFig)
  1612. {
  1613. ENTER(5);
  1614. Real *c, *a;
  1615. size_t mx, n;
  1616. GUARD_OBJ(a, GetVpValue(self, 1));
  1617. mx = a->Prec * (VpBaseFig() + 1);
  1618. n = GetPrecisionInt(nFig) + VpDblFig() + BASE_FIG;
  1619. if (mx <= n) mx = n;
  1620. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1621. VpSqrt(c, a);
  1622. return VpCheckGetValue(c);
  1623. }
  1624. /* Return the integer part of the number, as a BigDecimal.
  1625. */
  1626. static VALUE
  1627. BigDecimal_fix(VALUE self)
  1628. {
  1629. ENTER(5);
  1630. Real *c, *a;
  1631. size_t mx;
  1632. GUARD_OBJ(a, GetVpValue(self, 1));
  1633. mx = a->Prec *(VpBaseFig() + 1);
  1634. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1635. VpActiveRound(c, a, VP_ROUND_DOWN, 0); /* 0: round off */
  1636. return VpCheckGetValue(c);
  1637. }
  1638. /* call-seq:
  1639. * round(n, mode)
  1640. *
  1641. * Round to the nearest integer (by default), returning the result as a
  1642. * BigDecimal if n is specified, or as an Integer if it isn't.
  1643. *
  1644. * BigDecimal('3.14159').round #=> 3
  1645. * BigDecimal('8.7').round #=> 9
  1646. * BigDecimal('-9.9').round #=> -10
  1647. *
  1648. * BigDecimal('3.14159').round(2).class.name #=> "BigDecimal"
  1649. * BigDecimal('3.14159').round.class.name #=> "Integer"
  1650. *
  1651. * If n is specified and positive, the fractional part of the result has no
  1652. * more than that many digits.
  1653. *
  1654. * If n is specified and negative, at least that many digits to the left of the
  1655. * decimal point will be 0 in the result, and return value will be an Integer.
  1656. *
  1657. * BigDecimal('3.14159').round(3) #=> 3.142
  1658. * BigDecimal('13345.234').round(-2) #=> 13300
  1659. *
  1660. * The value of the optional mode argument can be used to determine how
  1661. * rounding is performed; see BigDecimal.mode.
  1662. */
  1663. static VALUE
  1664. BigDecimal_round(int argc, VALUE *argv, VALUE self)
  1665. {
  1666. ENTER(5);
  1667. Real *c, *a;
  1668. int iLoc = 0;
  1669. VALUE vLoc;
  1670. VALUE vRound;
  1671. int round_to_int = 0;
  1672. size_t mx, pl;
  1673. unsigned short sw = VpGetRoundMode();
  1674. switch (rb_scan_args(argc, argv, "02", &vLoc, &vRound)) {
  1675. case 0:
  1676. iLoc = 0;
  1677. round_to_int = 1;
  1678. break;
  1679. case 1:
  1680. if (RB_TYPE_P(vLoc, T_HASH)) {
  1681. sw = check_rounding_mode_option(vLoc);
  1682. }
  1683. else {
  1684. iLoc = NUM2INT(vLoc);
  1685. if (iLoc < 1) round_to_int = 1;
  1686. }
  1687. break;
  1688. case 2:
  1689. iLoc = NUM2INT(vLoc);
  1690. if (RB_TYPE_P(vRound, T_HASH)) {
  1691. sw = check_rounding_mode_option(vRound);
  1692. }
  1693. else {
  1694. sw = check_rounding_mode(vRound);
  1695. }
  1696. break;
  1697. default:
  1698. break;
  1699. }
  1700. pl = VpSetPrecLimit(0);
  1701. GUARD_OBJ(a, GetVpValue(self, 1));
  1702. mx = a->Prec * (VpBaseFig() + 1);
  1703. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1704. VpSetPrecLimit(pl);
  1705. VpActiveRound(c, a, sw, iLoc);
  1706. if (round_to_int) {
  1707. return BigDecimal_to_i(VpCheckGetValue(c));
  1708. }
  1709. return VpCheckGetValue(c);
  1710. }
  1711. /* call-seq:
  1712. * truncate(n)
  1713. *
  1714. * Truncate to the nearest integer (by default), returning the result as a
  1715. * BigDecimal.
  1716. *
  1717. * BigDecimal('3.14159').truncate #=> 3
  1718. * BigDecimal('8.7').truncate #=> 8
  1719. * BigDecimal('-9.9').truncate #=> -9
  1720. *
  1721. * If n is specified and positive, the fractional part of the result has no
  1722. * more than that many digits.
  1723. *
  1724. * If n is specified and negative, at least that many digits to the left of the
  1725. * decimal point will be 0 in the result.
  1726. *
  1727. * BigDecimal('3.14159').truncate(3) #=> 3.141
  1728. * BigDecimal('13345.234').truncate(-2) #=> 13300.0
  1729. */
  1730. static VALUE
  1731. BigDecimal_truncate(int argc, VALUE *argv, VALUE self)
  1732. {
  1733. ENTER(5);
  1734. Real *c, *a;
  1735. int iLoc;
  1736. VALUE vLoc;
  1737. size_t mx, pl = VpSetPrecLimit(0);
  1738. if (rb_scan_args(argc, argv, "01", &vLoc) == 0) {
  1739. iLoc = 0;
  1740. }
  1741. else {
  1742. iLoc = NUM2INT(vLoc);
  1743. }
  1744. GUARD_OBJ(a, GetVpValue(self, 1));
  1745. mx = a->Prec * (VpBaseFig() + 1);
  1746. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1747. VpSetPrecLimit(pl);
  1748. VpActiveRound(c, a, VP_ROUND_DOWN, iLoc); /* 0: truncate */
  1749. if (argc == 0) {
  1750. return BigDecimal_to_i(VpCheckGetValue(c));
  1751. }
  1752. return VpCheckGetValue(c);
  1753. }
  1754. /* Return the fractional part of the number, as a BigDecimal.
  1755. */
  1756. static VALUE
  1757. BigDecimal_frac(VALUE self)
  1758. {
  1759. ENTER(5);
  1760. Real *c, *a;
  1761. size_t mx;
  1762. GUARD_OBJ(a, GetVpValue(self, 1));
  1763. mx = a->Prec * (VpBaseFig() + 1);
  1764. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1765. VpFrac(c, a);
  1766. return VpCheckGetValue(c);
  1767. }
  1768. /* call-seq:
  1769. * floor(n)
  1770. *
  1771. * Return the largest integer less than or equal to the value, as a BigDecimal.
  1772. *
  1773. * BigDecimal('3.14159').floor #=> 3
  1774. * BigDecimal('-9.1').floor #=> -10
  1775. *
  1776. * If n is specified and positive, the fractional part of the result has no
  1777. * more than that many digits.
  1778. *
  1779. * If n is specified and negative, at least that
  1780. * many digits to the left of the decimal point will be 0 in the result.
  1781. *
  1782. * BigDecimal('3.14159').floor(3) #=> 3.141
  1783. * BigDecimal('13345.234').floor(-2) #=> 13300.0
  1784. */
  1785. static VALUE
  1786. BigDecimal_floor(int argc, VALUE *argv, VALUE self)
  1787. {
  1788. ENTER(5);
  1789. Real *c, *a;
  1790. int iLoc;
  1791. VALUE vLoc;
  1792. size_t mx, pl = VpSetPrecLimit(0);
  1793. if (rb_scan_args(argc, argv, "01", &vLoc)==0) {
  1794. iLoc = 0;
  1795. }
  1796. else {
  1797. iLoc = NUM2INT(vLoc);
  1798. }
  1799. GUARD_OBJ(a, GetVpValue(self, 1));
  1800. mx = a->Prec * (VpBaseFig() + 1);
  1801. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1802. VpSetPrecLimit(pl);
  1803. VpActiveRound(c, a, VP_ROUND_FLOOR, iLoc);
  1804. #ifdef BIGDECIMAL_DEBUG
  1805. VPrint(stderr, "floor: c=%\n", c);
  1806. #endif
  1807. if (argc == 0) {
  1808. return BigDecimal_to_i(VpCheckGetValue(c));
  1809. }
  1810. return VpCheckGetValue(c);
  1811. }
  1812. /* call-seq:
  1813. * ceil(n)
  1814. *
  1815. * Return the smallest integer greater than or equal to the value, as a BigDecimal.
  1816. *
  1817. * BigDecimal('3.14159').ceil #=> 4
  1818. * BigDecimal('-9.1').ceil #=> -9
  1819. *
  1820. * If n is specified and positive, the fractional part of the result has no
  1821. * more than that many digits.
  1822. *
  1823. * If n is specified and negative, at least that
  1824. * many digits to the left of the decimal point will be 0 in the result.
  1825. *
  1826. * BigDecimal('3.14159').ceil(3) #=> 3.142
  1827. * BigDecimal('13345.234').ceil(-2) #=> 13400.0
  1828. */
  1829. static VALUE
  1830. BigDecimal_ceil(int argc, VALUE *argv, VALUE self)
  1831. {
  1832. ENTER(5);
  1833. Real *c, *a;
  1834. int iLoc;
  1835. VALUE vLoc;
  1836. size_t mx, pl = VpSetPrecLimit(0);
  1837. if (rb_scan_args(argc, argv, "01", &vLoc) == 0) {
  1838. iLoc = 0;
  1839. } else {
  1840. iLoc = NUM2INT(vLoc);
  1841. }
  1842. GUARD_OBJ(a, GetVpValue(self, 1));
  1843. mx = a->Prec * (VpBaseFig() + 1);
  1844. GUARD_OBJ(c, VpCreateRbObject(mx, "0", true));
  1845. VpSetPrecLimit(pl);
  1846. VpActiveRound(c, a, VP_ROUND_CEIL, iLoc);
  1847. if (argc == 0) {
  1848. return BigDecimal_to_i(VpCheckGetValue(c));
  1849. }
  1850. return VpCheckGetValue(c);
  1851. }
  1852. /* call-seq:
  1853. * to_s(s)
  1854. *
  1855. * Converts the value to a string.
  1856. *
  1857. * The default format looks like 0.xxxxEnn.
  1858. *
  1859. * The optional parameter s consists of either an integer; or an optional '+'
  1860. * or ' ', followed by an optional number, followed by an optional 'E' or 'F'.
  1861. *
  1862. * If there is a '+' at the start of s, positive values are returned with
  1863. * a leading '+'.
  1864. *
  1865. * A space at the start of s returns positive values with a leading space.
  1866. *
  1867. * If s contains a number, a space is inserted after each group of that many
  1868. * fractional digits.
  1869. *
  1870. * If s ends with an 'E', engineering notation (0.xxxxEnn) is used.
  1871. *
  1872. * If s ends with an 'F', conventional floating point notation is used.
  1873. *
  1874. * Examples:
  1875. *
  1876. * BigDecimal('-123.45678901234567890').to_s('5F')
  1877. * #=> '-123.45678 90123 45678 9'
  1878. *
  1879. * BigDecimal('123.45678901234567890').to_s('+8F')
  1880. * #=> '+123.45678901 23456789'
  1881. *
  1882. * BigDecimal('123.45678901234567890').to_s(' F')
  1883. * #=> ' 123.4567890123456789'
  1884. */
  1885. static VALUE
  1886. BigDecimal_to_s(int argc, VALUE *argv, VALUE self)
  1887. {
  1888. ENTER(5);
  1889. int fmt = 0; /* 0: E format, 1: F format */
  1890. int fPlus = 0; /* 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
  1891. Real *vp;
  1892. volatile VALUE str;
  1893. char *psz;
  1894. char ch;
  1895. size_t nc, mc = 0;
  1896. SIGNED_VALUE m;
  1897. VALUE f;
  1898. GUARD_OBJ(vp, GetVpValue(self, 1));
  1899. if (rb_scan_args(argc, argv, "01", &f) == 1) {
  1900. if (RB_TYPE_P(f, T_STRING)) {
  1901. psz = StringValueCStr(f);
  1902. if (*psz == ' ') {
  1903. fPlus = 1;
  1904. psz++;
  1905. }
  1906. else if (*psz == '+') {
  1907. fPlus = 2;
  1908. psz++;
  1909. }
  1910. while ((ch = *psz++) != 0) {
  1911. if (ISSPACE(ch)) {
  1912. continue;
  1913. }
  1914. if (!ISDIGIT(ch)) {
  1915. if (ch == 'F' || ch == 'f') {
  1916. fmt = 1; /* F format */
  1917. }
  1918. break;
  1919. }
  1920. mc = mc*10 + ch - '0';
  1921. }
  1922. }
  1923. else {
  1924. m = NUM2INT(f);
  1925. if (m <= 0) {
  1926. rb_raise(rb_eArgError, "argument must be positive");
  1927. }
  1928. mc = (size_t)m;
  1929. }
  1930. }
  1931. if (fmt) {
  1932. nc = VpNumOfChars(vp, "F");
  1933. }
  1934. else {
  1935. nc = VpNumOfChars(vp, "E");
  1936. }
  1937. if (mc > 0) {
  1938. nc += (nc + mc - 1) / mc + 1;
  1939. }
  1940. str = rb_usascii_str_new(0, nc);
  1941. psz = RSTRING_PTR(str);
  1942. if (fmt) {
  1943. VpToFString(vp, psz, mc, fPlus);
  1944. }
  1945. else {
  1946. VpToString (vp, psz, mc, fPlus);
  1947. }
  1948. rb_str_resize(str, strlen(psz));
  1949. return str;
  1950. }
  1951. /* Splits a BigDecimal number into four parts, returned as an array of values.
  1952. *
  1953. * The first value represents the sign of the BigDecimal, and is -1 or 1, or 0
  1954. * if the BigDecimal is Not a Number.
  1955. *
  1956. * The second value is a string representing the significant digits of the
  1957. * BigDecimal, with no leading zeros.
  1958. *
  1959. * The third value is the base used for arithmetic (currently always 10) as an
  1960. * Integer.
  1961. *
  1962. * The fourth value is an Integer exponent.
  1963. *
  1964. * If the BigDecimal can be represented as 0.xxxxxx*10**n, then xxxxxx is the
  1965. * string of significant digits with no leading zeros, and n is the exponent.
  1966. *
  1967. * From these values, you can translate a BigDecimal to a float as follows:
  1968. *
  1969. * sign, significant_digits, base, exponent = a.split
  1970. * f = sign * "0.#{significant_digits}".to_f * (base ** exponent)
  1971. *
  1972. * (Note that the to_f method is provided as a more convenient way to translate
  1973. * a BigDecimal to a Float.)
  1974. */
  1975. static VALUE
  1976. BigDecimal_split(VALUE self)
  1977. {
  1978. ENTER(5);
  1979. Real *vp;
  1980. VALUE obj,str;
  1981. ssize_t e, s;
  1982. char *psz1;
  1983. GUARD_OBJ(vp, GetVpValue(self, 1));
  1984. str = rb_str_new(0, VpNumOfChars(vp, "E"));
  1985. psz1 = RSTRING_PTR(str);
  1986. VpSzMantissa(vp, psz1);
  1987. s = 1;
  1988. if(psz1[0] == '-') {
  1989. size_t len = strlen(psz1 + 1);
  1990. memmove(psz1, psz1 + 1, len);
  1991. psz1[len] = '\0';
  1992. s = -1;
  1993. }
  1994. if (psz1[0] == 'N') s = 0; /* NaN */
  1995. e = VpExponent10(vp);
  1996. obj = rb_ary_new2(4);
  1997. rb_ary_push(obj, INT2FIX(s));
  1998. rb_ary_push(obj, str);
  1999. rb_str_resize(str, strlen(psz1));
  2000. rb_ary_push(obj, INT2FIX(10));
  2001. rb_ary_push(obj, SSIZET2NUM(e));
  2002. return obj;
  2003. }
  2004. /* Returns the exponent of the BigDecimal number, as an Integer.
  2005. *
  2006. * If the number can be represented as 0.xxxxxx*10**n where xxxxxx is a string
  2007. * of digits with no leading zeros, then n is the exponent.
  2008. */
  2009. static VALUE
  2010. BigDecimal_exponent(VALUE self)
  2011. {
  2012. ssize_t e = VpExponent10(GetVpValue(self, 1));
  2013. return SSIZET2NUM(e);
  2014. }
  2015. /* Returns a string representation of self.
  2016. *
  2017. * BigDecimal("1234.5678").inspect
  2018. * #=> "0.12345678e4"
  2019. */
  2020. static VALUE
  2021. BigDecimal_inspect(VALUE self)
  2022. {
  2023. ENTER(5);
  2024. Real *vp;
  2025. volatile VALUE str;
  2026. size_t nc;
  2027. GUARD_OBJ(vp, GetVpValue(self, 1));
  2028. nc = VpNumOfChars(vp, "E");
  2029. str = rb_str_new(0, nc);
  2030. VpToString(vp, RSTRING_PTR(str), 0, 0);
  2031. rb_str_resize(str, strlen(RSTRING_PTR(str)));
  2032. return str;
  2033. }
  2034. static VALUE BigMath_s_exp(VALUE, VALUE, VALUE);
  2035. static VALUE BigMath_s_log(VALUE, VALUE, VALUE);
  2036. #define BigMath_exp(x, n) BigMath_s_exp(rb_mBigMath, (x), (n))
  2037. #define BigMath_log(x, n) BigMath_s_log(rb_mBigMath, (x), (n))
  2038. inline static int
  2039. is_integer(VALUE x)
  2040. {
  2041. return (RB_TYPE_P(x, T_FIXNUM) || RB_TYPE_P(x, T_BIGNUM));
  2042. }
  2043. inline static int
  2044. is_negative(VALUE x)
  2045. {
  2046. if (FIXNUM_P(x)) {
  2047. return FIX2LONG(x) < 0;
  2048. }
  2049. else if (RB_TYPE_P(x, T_BIGNUM)) {
  2050. return FIX2INT(rb_big_cmp(x, INT2FIX(0))) < 0;
  2051. }
  2052. else if (RB_TYPE_P(x, T_FLOAT)) {
  2053. return RFLOAT_VALUE(x) < 0.0;
  2054. }
  2055. return RTEST(rb_funcall(x, '<', 1, INT2FIX(0)));
  2056. }
  2057. #define is_positive(x) (!is_negative(x))
  2058. inline static int
  2059. is_zero(VALUE x)
  2060. {
  2061. VALUE num;
  2062. switch (TYPE(x)) {
  2063. case T_FIXNUM:
  2064. return FIX2LONG(x) == 0;
  2065. case T_BIGNUM:
  2066. return Qfalse;
  2067. case T_RATIONAL:
  2068. num = rb_rational_num(x);
  2069. return FIXNUM_P(num) && FIX2LONG(num) == 0;
  2070. default:
  2071. break;
  2072. }
  2073. return RTEST(rb_funcall(x, id_eq, 1, INT2FIX(0)));
  2074. }
  2075. inline static int
  2076. is_one(VALUE x)
  2077. {
  2078. VALUE num, den;
  2079. switch (TYPE(x)) {
  2080. case T_FIXNUM:
  2081. return FIX2LONG(x) == 1;
  2082. case T_BIGNUM:
  2083. return Qfalse;
  2084. case T_RATIONAL:
  2085. num = rb_rational_num(x);
  2086. den = rb_rational_den(x);
  2087. return FIXNUM_P(den) && FIX2LONG(den) == 1 &&
  2088. FIXNUM_P(num) && FIX2LONG(num) == 1;
  2089. default:
  2090. break;
  2091. }
  2092. return RTEST(rb_funcall(x, id_eq, 1, INT2FIX(1)));
  2093. }
  2094. inline static int
  2095. is_even(VALUE x)
  2096. {
  2097. switch (TYPE(x)) {
  2098. case T_FIXNUM:
  2099. return (FIX2LONG(x) % 2) == 0;
  2100. case T_BIGNUM:
  2101. {
  2102. unsigned long l;
  2103. rb_big_pack(x, &l, 1);
  2104. return l % 2 == 0;
  2105. }
  2106. default:
  2107. break;
  2108. }
  2109. return 0;
  2110. }
  2111. static VALUE
  2112. bigdecimal_power_by_bigdecimal(Real const* x, Real const* exp, ssize_t const n)
  2113. {
  2114. VALUE log_x, multiplied, y;
  2115. volatile VALUE obj = exp->obj;
  2116. if (VpIsZero(exp)) {
  2117. return VpCheckGetValue(VpCreateRbObject(n, "1", true));
  2118. }
  2119. log_x = BigMath_log(x->obj, SSIZET2NUM(n+1));
  2120. multiplied = BigDecimal_mult2(exp->obj, log_x, SSIZET2NUM(n+1));
  2121. y = BigMath_exp(multiplied, SSIZET2NUM(n));
  2122. RB_GC_GUARD(obj);
  2123. return y;
  2124. }
  2125. /* call-seq:
  2126. * power(n)
  2127. * power(n, prec)
  2128. *
  2129. * Returns the value raised to the power of n.
  2130. *
  2131. * Note that n must be an Integer.
  2132. *
  2133. * Also available as the operator **.
  2134. */
  2135. static VALUE
  2136. BigDecimal_power(int argc, VALUE*argv, VALUE self)
  2137. {
  2138. ENTER(5);
  2139. VALUE vexp, prec;
  2140. Real* exp = NULL;
  2141. Real *x, *y;
  2142. ssize_t mp, ma, n;
  2143. SIGNED_VALUE int_exp;
  2144. double d;
  2145. rb_scan_args(argc, argv, "11", &vexp, &prec);
  2146. GUARD_OBJ(x, GetVpValue(self, 1));
  2147. n = NIL_P(prec) ? (ssize_t)(x->Prec*VpBaseFig()) : NUM2SSIZET(prec);
  2148. if (VpIsNaN(x)) {
  2149. y = VpCreateRbObject(n, "0", true);
  2150. RB_GC_GUARD(y->obj);
  2151. VpSetNaN(y);
  2152. return VpCheckGetValue(y);
  2153. }
  2154. retry:
  2155. switch (TYPE(vexp)) {
  2156. case T_FIXNUM:
  2157. break;
  2158. case T_BIGNUM:
  2159. break;
  2160. case T_FLOAT:
  2161. d = RFLOAT_VALUE(vexp);
  2162. if (d == round(d)) {
  2163. if (FIXABLE(d)) {
  2164. vexp = LONG2FIX((long)d);
  2165. }
  2166. else {
  2167. vexp = rb_dbl2big(d);
  2168. }
  2169. goto retry;
  2170. }
  2171. if (NIL_P(prec)) {
  2172. n += BIGDECIMAL_DOUBLE_FIGURES;
  2173. }
  2174. exp = GetVpValueWithPrec(vexp, 0, 1);
  2175. break;
  2176. case T_RATIONAL:
  2177. if (is_zero(rb_rational_num(vexp))) {
  2178. if (is_positive(vexp)) {
  2179. vexp = INT2FIX(0);
  2180. goto retry;
  2181. }
  2182. }
  2183. else if (is_one(rb_rational_den(vexp))) {
  2184. vexp = rb_rational_num(vexp);
  2185. goto retry;
  2186. }
  2187. exp = GetVpValueWithPrec(vexp, n, 1);
  2188. if (NIL_P(prec)) {
  2189. n += n;
  2190. }
  2191. break;
  2192. case T_DATA:
  2193. if (is_kind_of_BigDecimal(vexp)) {
  2194. VALUE zero = INT2FIX(0);
  2195. VALUE rounded = BigDecimal_round(1, &zero, vexp);
  2196. if (RTEST(BigDecimal_eq(vexp, rounded))) {
  2197. vexp = BigDecimal_to_i(vexp);
  2198. goto retry;
  2199. }
  2200. if (NIL_P(prec)) {
  2201. GUARD_OBJ(y, GetVpValue(vexp, 1));
  2202. n += y->Prec*VpBaseFig();
  2203. }
  2204. exp = DATA_PTR(vexp);
  2205. break;
  2206. }
  2207. /* fall through */
  2208. default:
  2209. rb_raise(rb_eTypeError,
  2210. "wrong argument type %"PRIsVALUE" (expected scalar Numeric)",
  2211. RB_OBJ_CLASSNAME(vexp));
  2212. }
  2213. if (VpIsZero(x)) {
  2214. if (is_negative(vexp)) {
  2215. y = VpCreateRbObject(n, "#0", true);
  2216. RB_GC_GUARD(y->obj);
  2217. if (BIGDECIMAL_NEGATIVE_P(x)) {
  2218. if (is_integer(vexp)) {
  2219. if (is_even(vexp)) {
  2220. /* (-0) ** (-even_integer) -> Infinity */
  2221. VpSetPosInf(y);
  2222. }
  2223. else {
  2224. /* (-0) ** (-odd_integer) -> -Infinity */
  2225. VpSetNegInf(y);
  2226. }
  2227. }
  2228. else {
  2229. /* (-0) ** (-non_integer) -> Infinity */
  2230. VpSetPosInf(y);
  2231. }
  2232. }
  2233. else {
  2234. /* (+0) ** (-num) -> Infinity */
  2235. VpSetPosInf(y);
  2236. }
  2237. return VpCheckGetValue(y);
  2238. }
  2239. else if (is_zero(vexp)) {
  2240. return VpCheckGetValue(VpCreateRbObject(n, "1", true));
  2241. }
  2242. else {
  2243. return VpCheckGetValue(VpCreateRbObject(n, "0", true));
  2244. }
  2245. }
  2246. if (is_zero(vexp)) {
  2247. return VpCheckGetValue(VpCreateRbObject(n, "1", true));
  2248. }
  2249. else if (is_one(vexp)) {
  2250. return self;
  2251. }
  2252. if (VpIsInf(x)) {
  2253. if (is_negative(vexp)) {
  2254. if (BIGDECIMAL_NEGATIVE_P(x)) {
  2255. if (is_integer(vexp)) {
  2256. if (is_even(vexp)) {
  2257. /* (-Infinity) ** (-even_integer) -> +0 */
  2258. return VpCheckGetValue(VpCreateRbObject(n, "0", true));
  2259. }
  2260. else {
  2261. /* (-Infinity) ** (-odd_integer) -> -0 */
  2262. return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
  2263. }
  2264. }
  2265. else {
  2266. /* (-Infinity) ** (-non_integer) -> -0 */
  2267. return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
  2268. }
  2269. }
  2270. else {
  2271. return VpCheckGetValue(VpCreateRbObject(n, "0", true));
  2272. }
  2273. }
  2274. else {
  2275. y = VpCreateRbObject(n, "0", true);
  2276. if (BIGDECIMAL_NEGATIVE_P(x)) {
  2277. if (is_integer(vexp)) {
  2278. if (is_even(vexp)) {
  2279. VpSetPosInf(y);
  2280. }
  2281. else {
  2282. VpSetNegInf(y);
  2283. }
  2284. }
  2285. else {
  2286. /* TODO: support complex */
  2287. rb_raise(rb_eMathDomainError,
  2288. "a non-integral exponent for a negative base");
  2289. }
  2290. }
  2291. else {
  2292. VpSetPosInf(y);
  2293. }
  2294. return VpCheckGetValue(y);
  2295. }
  2296. }
  2297. if (exp != NULL) {
  2298. return bigdecimal_power_by_bigdecimal(x, exp, n);
  2299. }
  2300. else if (RB_TYPE_P(vexp, T_BIGNUM)) {
  2301. VALUE abs_value = BigDecimal_abs(self);
  2302. if (is_one(abs_value)) {
  2303. return VpCheckGetValue(VpCreateRbObject(n, "1", true));
  2304. }
  2305. else if (RTEST(rb_funcall(abs_value, '<', 1, INT2FIX(1)))) {
  2306. if (is_negative(vexp)) {
  2307. y = VpCreateRbObject(n, "0", true);
  2308. if (is_even(vexp)) {
  2309. VpSetInf(y, VpGetSign(x));
  2310. }
  2311. else {
  2312. VpSetInf(y, -VpGetSign(x));
  2313. }
  2314. return VpCheckGetValue(y);
  2315. }
  2316. else if (BIGDECIMAL_NEGATIVE_P(x) && is_even(vexp)) {
  2317. return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
  2318. }
  2319. else {
  2320. return VpCheckGetValue(VpCreateRbObject(n, "0", true));
  2321. }
  2322. }
  2323. else {
  2324. if (is_positive(vexp)) {
  2325. y = VpCreateRbObject(n, "0", true);
  2326. if (is_even(vexp)) {
  2327. VpSetInf(y, VpGetSign(x));
  2328. }
  2329. else {
  2330. VpSetInf(y, -VpGetSign(x));
  2331. }
  2332. return VpCheckGetValue(y);
  2333. }
  2334. else if (BIGDECIMAL_NEGATIVE_P(x) && is_even(vexp)) {
  2335. return VpCheckGetValue(VpCreateRbObject(n, "-0", true));
  2336. }
  2337. else {
  2338. return VpCheckGetValue(VpCreateRbObject(n, "0", true));
  2339. }
  2340. }
  2341. }
  2342. int_exp = FIX2LONG(vexp);
  2343. ma = int_exp;
  2344. if (ma < 0) ma = -ma;
  2345. if (ma == 0) ma = 1;
  2346. if (VpIsDef(x)) {
  2347. mp = x->Prec * (VpBaseFig() + 1);
  2348. GUARD_OBJ(y, VpCreateRbObject(mp * (ma + 1), "0", true));
  2349. }
  2350. else {
  2351. GUARD_OBJ(y, VpCreateRbObject(1, "0", true));
  2352. }
  2353. VpPowerByInt(y, x, int_exp);
  2354. if (!NIL_P(prec) && VpIsDef(y)) {
  2355. VpMidRound(y, VpGetRoundMode(), n);
  2356. }
  2357. return VpCheckGetValue(y);
  2358. }
  2359. /* call-seq:
  2360. * a ** n -> bigdecimal
  2361. *
  2362. * Returns the value raised to the power of n.
  2363. *
  2364. * See BigDecimal#power.
  2365. */
  2366. static VALUE
  2367. BigDecimal_power_op(VALUE self, VALUE exp)
  2368. {
  2369. return BigDecimal_power(1, &exp, self);
  2370. }
  2371. /* :nodoc:
  2372. *
  2373. * private method for dup and clone the provided BigDecimal +other+
  2374. */
  2375. static VALUE
  2376. BigDecimal_initialize_copy(VALUE self, VALUE other)
  2377. {
  2378. Real *pv = rb_check_typeddata(self, &BigDecimal_data_type);
  2379. Real *x = rb_check_typeddata(other, &BigDecimal_data_type);
  2380. if (self != other) {
  2381. DATA_PTR(self) = VpCopy(pv, x);
  2382. }
  2383. return self;
  2384. }
  2385. static VALUE
  2386. BigDecimal_clone(VALUE self)
  2387. {
  2388. return self;
  2389. }
  2390. #ifdef HAVE_RB_OPTS_EXCEPTION_P
  2391. int rb_opts_exception_p(VALUE opts, int default_value);
  2392. #define opts_exception_p(opts) rb_opts_exception_p((opts), 1)
  2393. #else
  2394. static int
  2395. opts_exception_p(VALUE opts)
  2396. {
  2397. static ID kwds[1];
  2398. VALUE exception;
  2399. if (!kwds[0]) {
  2400. kwds[0] = rb_intern_const("exception");
  2401. }
  2402. if (!rb_get_kwargs(opts, kwds, 0, 1, &exception)) return 1;
  2403. switch (exception) {
  2404. case Qtrue: case Qfalse:
  2405. break;
  2406. default:
  2407. rb_raise(rb_eArgError, "true or false is expected as exception: %+"PRIsVALUE,
  2408. exception);
  2409. }
  2410. return exception != Qfalse;
  2411. }
  2412. #endif
  2413. static VALUE
  2414. check_exception(VALUE bd)
  2415. {
  2416. assert(is_kind_of_BigDecimal(bd));
  2417. Real *vp;
  2418. TypedData_Get_Struct(bd, Real, &BigDecimal_data_type, vp);
  2419. VpCheckGetValue(vp); /* VpCheckGetValue performs exception check */
  2420. return bd;
  2421. }
  2422. static VALUE
  2423. rb_uint64_convert_to_BigDecimal(uint64_t uval, RB_UNUSED_VAR(size_t digs), int raise_exception)
  2424. {
  2425. VALUE obj = TypedData_Wrap_Struct(rb_cBigDecimal, &BigDecimal_data_type, 0);
  2426. Real *vp;
  2427. if (uval == 0) {
  2428. vp = VpAllocReal(1);
  2429. vp->MaxPrec = 1;
  2430. vp->Prec = 1;
  2431. vp->exponent = 1;
  2432. VpSetZero(vp, 1);
  2433. vp->frac[0] = 0;
  2434. }
  2435. else if (uval < BASE) {
  2436. vp = VpAllocReal(1);
  2437. vp->MaxPrec = 1;
  2438. vp->Prec = 1;
  2439. vp->exponent = 1;
  2440. VpSetSign(vp, 1);
  2441. vp->frac[0] = (DECDIG)uval;
  2442. }
  2443. else {
  2444. DECDIG buf[BIGDECIMAL_INT64_MAX_LENGTH] = {0,};
  2445. size_t exp = 0, ntz = 0;
  2446. for (; uval > 0; ++exp) {
  2447. DECDIG r = uval % BASE;
  2448. if (r == 0) ++ntz;
  2449. buf[BIGDECIMAL_INT64_MAX_LENGTH - exp - 1] = r;
  2450. uval /= BASE;
  2451. }
  2452. const size_t len = exp - ntz;
  2453. vp = VpAllocReal(len);
  2454. vp->MaxPrec = len;
  2455. vp->Prec = len;
  2456. vp->exponent = exp;
  2457. VpSetSign(vp, 1);
  2458. MEMCPY(vp->frac, buf + BIGDECIMAL_INT64_MAX_LENGTH - exp, DECDIG, len);
  2459. }
  2460. return BigDecimal_wrap_struct(obj, vp);
  2461. }
  2462. static VALUE
  2463. rb_int64_convert_to_BigDecimal(int64_t ival, size_t digs, int raise_exception)
  2464. {
  2465. const uint64_t uval = (ival < 0) ? (((uint64_t)-(ival+1))+1) : (uint64_t)ival;
  2466. VALUE bd = rb_uint64_convert_to_BigDecimal(uval, digs, raise_exception);
  2467. if (ival < 0) {
  2468. Real *vp;
  2469. TypedData_Get_Struct(bd, Real, &BigDecimal_data_type, vp);
  2470. VpSetSign(vp, -1);
  2471. }
  2472. return bd;
  2473. }
  2474. static VALUE
  2475. rb_big_convert_to_BigDecimal(VALUE val, RB_UNUSED_VAR(size_t digs), int raise_exception)
  2476. {
  2477. assert(RB_TYPE_P(val, T_BIGNUM));
  2478. size_t size = rb_absint_size(val, NULL);
  2479. int sign = FIX2INT(rb_big_cmp(val, INT2FIX(0)));
  2480. if (size <= sizeof(long)) {
  2481. if (sign < 0) {
  2482. return rb_int64_convert_to_BigDecimal(NUM2LONG(val), digs, raise_exception);
  2483. }
  2484. else {
  2485. return rb_uint64_convert_to_BigDecimal(NUM2ULONG(val), digs, raise_exception);
  2486. }
  2487. }
  2488. #if defined(SIZEOF_LONG_LONG) && SIZEOF_LONG < SIZEOF_LONG_LONG
  2489. else if (size <= sizeof(LONG_LONG)) {
  2490. if (sign < 0) {
  2491. return rb_int64_convert_to_BigDecimal(NUM2LL(val), digs, raise_exception);
  2492. }
  2493. else {
  2494. return rb_uint64_convert_to_BigDecimal(NUM2ULL(val), digs, raise_exception);
  2495. }
  2496. }
  2497. #endif
  2498. else {
  2499. VALUE str = rb_big2str(val, 10);
  2500. Real *vp = VpCreateRbObject(RSTRING_LEN(str) + BASE_FIG + 1,
  2501. RSTRING_PTR(str), true);
  2502. RB_GC_GUARD(str);
  2503. return check_exception(vp->obj);
  2504. }
  2505. }
  2506. static VALUE
  2507. rb_inum_convert_to_BigDecimal(VALUE val, RB_UNUSED_VAR(size_t digs), int raise_exception)
  2508. {
  2509. assert(RB_INTEGER_TYPE_P(val));
  2510. if (FIXNUM_P(val)) {
  2511. return rb_int64_convert_to_BigDecimal(FIX2LONG(val), digs, raise_exception);
  2512. }
  2513. else {
  2514. return rb_big_convert_to_BigDecimal(val, digs, raise_exception);
  2515. }
  2516. }
  2517. static VALUE
  2518. rb_float_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
  2519. {
  2520. assert(RB_FLOAT_TYPE_P(val));
  2521. double d = RFLOAT_VALUE(val);
  2522. if (isnan(d)) {
  2523. VALUE obj = BigDecimal_nan();
  2524. return check_exception(obj);
  2525. }
  2526. else if (isinf(d)) {
  2527. VALUE obj;
  2528. if (d > 0) {
  2529. obj = BigDecimal_positive_infinity();
  2530. }
  2531. else {
  2532. obj = BigDecimal_negative_infinity();
  2533. }
  2534. return check_exception(obj);
  2535. }
  2536. else if (d == 0.0) {
  2537. if (1/d < 0.0) {
  2538. return BigDecimal_negative_zero();
  2539. }
  2540. else {
  2541. return BigDecimal_positive_zero();
  2542. }
  2543. }
  2544. if (digs == SIZE_MAX) {
  2545. if (!raise_exception)
  2546. return Qnil;
  2547. rb_raise(rb_eArgError,
  2548. "can't omit precision for a %"PRIsVALUE".",
  2549. CLASS_OF(val));
  2550. }
  2551. else if (digs > BIGDECIMAL_DOUBLE_FIGURES) {
  2552. if (!raise_exception)
  2553. return Qnil;
  2554. rb_raise(rb_eArgError, "precision too large.");
  2555. }
  2556. /* Use the same logic in flo_to_s to convert a float to a decimal string */
  2557. char buf[BIGDECIMAL_DOUBLE_FIGURES + BASE_FIG + 2 + 1]; /* sizeof(buf) == 28 in the typical case */
  2558. int decpt, negative_p;
  2559. char *e;
  2560. const int mode = digs == 0 ? 0 : 2;
  2561. char *p = BigDecimal_dtoa(d, mode, (int)digs, &decpt, &negative_p, &e);
  2562. int len10 = (int)(e - p);
  2563. if (len10 > BIGDECIMAL_DOUBLE_FIGURES) {
  2564. /* TODO: Presumably, rounding should be done here. */
  2565. len10 = BIGDECIMAL_DOUBLE_FIGURES;
  2566. }
  2567. memcpy(buf, p, len10);
  2568. xfree(p);
  2569. VALUE inum;
  2570. size_t RB_UNUSED_VAR(prec) = 0;
  2571. size_t exp = 0;
  2572. if (decpt > 0) {
  2573. if (decpt < len10) {
  2574. /*
  2575. * len10 |---------------|
  2576. * : |-------| frac_len10 = len10 - decpt
  2577. * decpt |-------| |--| ntz10 = BASE_FIG - frac_len10 % BASE_FIG
  2578. * : : :
  2579. * 00 dd dddd.dddd dd 00
  2580. * prec |-----.----.----.-----| prec = exp + roomof(frac_len, BASE_FIG)
  2581. * exp |-----.----| exp = roomof(decpt, BASE_FIG)
  2582. */
  2583. const size_t frac_len10 = len10 - decpt;
  2584. const size_t ntz10 = BASE_FIG - frac_len10 % BASE_FIG;
  2585. memset(buf + len10, '0', ntz10);
  2586. buf[len10 + ntz10] = '\0';
  2587. inum = rb_cstr_to_inum(buf, 10, false);
  2588. exp = roomof(decpt, BASE_FIG);
  2589. prec = exp + roomof(frac_len10, BASE_FIG);
  2590. }
  2591. else {
  2592. /*
  2593. * decpt |-----------------------|
  2594. * len10 |----------| :
  2595. * : |------------| exp10
  2596. * : : :
  2597. * 00 dd dddd dd 00 0000 0000.0
  2598. * : : : :
  2599. * : |--| ntz10 = exp10 % BASE_FIG
  2600. * prec |-----.----.-----| :
  2601. * : |----.----| exp10 / BASE_FIG
  2602. * exp |-----.----.-----.----.----|
  2603. */
  2604. const size_t exp10 = decpt - len10;
  2605. const size_t ntz10 = exp10 % BASE_FIG;
  2606. memset(buf + len10, '0', ntz10);
  2607. buf[len10 + ntz10] = '\0';
  2608. inum = rb_cstr_to_inum(buf, 10, false);
  2609. prec = roomof(len10 + ntz10, BASE_FIG);
  2610. exp = prec + exp10 / BASE_FIG;
  2611. }
  2612. }
  2613. else if (decpt == 0) {
  2614. /*
  2615. * len10 |------------|
  2616. * : :
  2617. * 0.dddd dddd dd 00
  2618. * : : :
  2619. * : |--| ntz10 = prec * BASE_FIG - len10
  2620. * prec |----.----.-----| roomof(len10, BASE_FIG)
  2621. */
  2622. prec = roomof(len10, BASE_FIG);
  2623. const size_t ntz10 = prec * BASE_FIG - len10;
  2624. memset(buf + len10, '0', ntz10);
  2625. buf[len10 + ntz10] = '\0';
  2626. inum = rb_cstr_to_inum(buf, 10, false);
  2627. }
  2628. else {
  2629. /*
  2630. * len10 |---------------|
  2631. * : :
  2632. * decpt |-------| |--| ntz10 = prec * BASE_FIG - nlz10 - len10
  2633. * : : :
  2634. * 0.0000 00 dd dddd dddd dd 00
  2635. * : : :
  2636. * nlz10 |--| : decpt % BASE_FIG
  2637. * prec |-----.----.----.-----| roomof(decpt + len10, BASE_FIG) - exp
  2638. * exp |----| decpt / BASE_FIG
  2639. */
  2640. decpt = -decpt;
  2641. const size_t nlz10 = decpt % BASE_FIG;
  2642. exp = decpt / BASE_FIG;
  2643. prec = roomof(decpt + len10, BASE_FIG) - exp;
  2644. const size_t ntz10 = prec * BASE_FIG - nlz10 - len10;
  2645. if (nlz10 > 0) {
  2646. memmove(buf + nlz10, buf, len10);
  2647. memset(buf, '0', nlz10);
  2648. }
  2649. memset(buf + nlz10 + len10, '0', ntz10);
  2650. buf[nlz10 + len10 + ntz10] = '\0';
  2651. inum = rb_cstr_to_inum(buf, 10, false);
  2652. exp = -exp;
  2653. }
  2654. VALUE bd = rb_inum_convert_to_BigDecimal(inum, SIZE_MAX, raise_exception);
  2655. Real *vp;
  2656. TypedData_Get_Struct(bd, Real, &BigDecimal_data_type, vp);
  2657. assert(vp->Prec == prec);
  2658. vp->exponent = exp;
  2659. if (negative_p) VpSetSign(vp, -1);
  2660. return bd;
  2661. }
  2662. static VALUE
  2663. rb_rational_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
  2664. {
  2665. assert(RB_TYPE_P(val, T_RATIONAL));
  2666. if (digs == SIZE_MAX) {
  2667. if (!raise_exception)
  2668. return Qnil;
  2669. rb_raise(rb_eArgError,
  2670. "can't omit precision for a %"PRIsVALUE".",
  2671. CLASS_OF(val));
  2672. }
  2673. VALUE num = rb_inum_convert_to_BigDecimal(rb_rational_num(val), 0, raise_exception);
  2674. VALUE d = BigDecimal_div2(num, rb_rational_den(val), SIZET2NUM(digs));
  2675. return d;
  2676. }
  2677. static VALUE
  2678. rb_cstr_convert_to_BigDecimal(const char *c_str, size_t digs, int raise_exception)
  2679. {
  2680. if (digs == SIZE_MAX)
  2681. digs = 0;
  2682. Real *vp = VpCreateRbObject(digs, c_str, raise_exception);
  2683. if (!vp)
  2684. return Qnil;
  2685. return VpCheckGetValue(vp);
  2686. }
  2687. static inline VALUE
  2688. rb_str_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
  2689. {
  2690. const char *c_str = StringValueCStr(val);
  2691. return rb_cstr_convert_to_BigDecimal(c_str, digs, raise_exception);
  2692. }
  2693. static VALUE
  2694. rb_convert_to_BigDecimal(VALUE val, size_t digs, int raise_exception)
  2695. {
  2696. switch (val) {
  2697. case Qnil:
  2698. case Qtrue:
  2699. case Qfalse:
  2700. if (raise_exception) {
  2701. const char *cname = NIL_P(val) ? "nil" :
  2702. val == Qtrue ? "true" :
  2703. val == Qfalse ? "false" :
  2704. NULL;
  2705. rb_raise(rb_eTypeError,
  2706. "can't convert %s into BigDecimal", cname);
  2707. }
  2708. return Qnil;
  2709. default:
  2710. break;
  2711. }
  2712. if (is_kind_of_BigDecimal(val)) {
  2713. if (digs == SIZE_MAX)
  2714. return check_exception(val);
  2715. Real *vp;
  2716. TypedData_Get_Struct(val, Real, &BigDecimal_data_type, vp);
  2717. VALUE copy = TypedData_Wrap_Struct(rb_cBigDecimal, &BigDecimal_data_type, 0);
  2718. vp = VpCopy(NULL, vp);
  2719. /* TODO: rounding */
  2720. BigDecimal_wrap_struct(copy, vp);
  2721. return VpCheckGetValue(vp);
  2722. }
  2723. else if (RB_INTEGER_TYPE_P(val)) {
  2724. return rb_inum_convert_to_BigDecimal(val, digs, raise_exception);
  2725. }
  2726. else if (RB_FLOAT_TYPE_P(val)) {
  2727. return rb_float_convert_to_BigDecimal(val, digs, raise_exception);
  2728. }
  2729. else if (RB_TYPE_P(val, T_RATIONAL)) {
  2730. return rb_rational_convert_to_BigDecimal(val, digs, raise_exception);
  2731. }
  2732. else if (RB_TYPE_P(val, T_COMPLEX)) {
  2733. VALUE im = rb_complex_imag(val);
  2734. if (!is_zero(im)) {
  2735. /* TODO: handle raise_exception */
  2736. rb_raise(rb_eArgError,
  2737. "Unable to make a BigDecimal from non-zero imaginary number");
  2738. }
  2739. return rb_convert_to_BigDecimal(rb_complex_real(val), digs, raise_exception);
  2740. }
  2741. else if (RB_TYPE_P(val, T_STRING)) {
  2742. return rb_str_convert_to_BigDecimal(val, digs, raise_exception);
  2743. }
  2744. /* TODO: chheck to_d */
  2745. /* TODO: chheck to_int */
  2746. VALUE str = rb_check_convert_type(val, T_STRING, "String", "to_str");
  2747. if (!RB_TYPE_P(str, T_STRING)) {
  2748. if (raise_exception) {
  2749. rb_raise(rb_eTypeError,
  2750. "can't convert %"PRIsVALUE" into BigDecimal", rb_obj_class(val));
  2751. }
  2752. return Qnil;
  2753. }
  2754. return rb_str_convert_to_BigDecimal(str, digs, raise_exception);
  2755. }
  2756. /* call-seq:
  2757. * BigDecimal(arg, exception: true)
  2758. * BigDecimal(arg, digits, exception: true)
  2759. *
  2760. * Returns <i>arg</i> converted to a BigDecimal. Numeric types are converted
  2761. * directly. Other types except for String are first converted to String
  2762. * by <code>to_str</code>. Strings can be converted when it has appropriate
  2763. * forms of decimal numbers. Exceptions can be suppressed by passing
  2764. * <code>exception: false</code>.
  2765. *
  2766. * When <i>arg</i> is a Float and <i>digits</i> is <code>0</code>, the number
  2767. * of digits is determined by the algorithm of <code>dtoa</code> function
  2768. * written by David M. Gay. That algorithm is based on "How to Print Floating-
  2769. * Point Numbers Accurately" by Guy L. Steele, Jr. and Jon L. White [Proc. ACM
  2770. * SIGPLAN '90, pp. 112-126].
  2771. *
  2772. * arg:: The value converted to a BigDecimal.
  2773. *
  2774. * If it is a String, spaces are ignored and unrecognized characters
  2775. * terminate the value.
  2776. *
  2777. * digits:: The number of significant digits, as an Integer. If omitted,
  2778. * the number of significant digits is determined from <i>arg</i>.
  2779. *
  2780. * The actual number of significant digits used in computation is
  2781. * usually larger than the specified number.
  2782. *
  2783. * exception:: Whether an exception should be raised on invalid arguments.
  2784. * +true+ by default, if passed +false+, just returns +nil+
  2785. * for invalid.
  2786. *
  2787. *
  2788. * ==== Exceptions
  2789. *
  2790. * TypeError:: If the +initial+ type is neither Integer, Float,
  2791. * Rational, nor BigDecimal, this exception is raised.
  2792. *
  2793. * TypeError:: If the +digits+ is not an Integer, this exception is raised.
  2794. *
  2795. * ArgumentError:: If +initial+ is a Float, and the +digits+ is larger than
  2796. * Float::DIG + 1, this exception is raised.
  2797. *
  2798. * ArgumentError:: If the +initial+ is a Float or Rational, and the +digits+
  2799. * value is omitted, this exception is raised.
  2800. */
  2801. static VALUE
  2802. f_BigDecimal(int argc, VALUE *argv, VALUE self)
  2803. {
  2804. VALUE val, digs_v, opts = Qnil;
  2805. argc = rb_scan_args(argc, argv, "11:", &val, &digs_v, &opts);
  2806. int exception = opts_exception_p(opts);
  2807. size_t digs = SIZE_MAX; /* this means digs is omitted */
  2808. if (argc > 1) {
  2809. digs_v = rb_to_int(digs_v);
  2810. if (FIXNUM_P(digs_v)) {
  2811. long n = FIX2LONG(digs_v);
  2812. if (n < 0)
  2813. goto negative_digs;
  2814. digs = (size_t)n;
  2815. }
  2816. else {
  2817. if (RBIGNUM_NEGATIVE_P(digs_v)) {
  2818. negative_digs:
  2819. if (!exception)
  2820. return Qnil;
  2821. rb_raise(rb_eArgError, "negative precision");
  2822. }
  2823. digs = NUM2SIZET(digs_v);
  2824. }
  2825. }
  2826. return rb_convert_to_BigDecimal(val, digs, exception);
  2827. }
  2828. static VALUE
  2829. BigDecimal_s_interpret_loosely(VALUE klass, VALUE str)
  2830. {
  2831. char const *c_str = StringValueCStr(str);
  2832. Real *vp = VpNewRbClass(0, c_str, klass, false, true);
  2833. if (!vp)
  2834. return Qnil;
  2835. else
  2836. return VpCheckGetValue(vp);
  2837. }
  2838. /* call-seq:
  2839. * BigDecimal.limit(digits)
  2840. *
  2841. * Limit the number of significant digits in newly created BigDecimal
  2842. * numbers to the specified value. Rounding is performed as necessary,
  2843. * as specified by BigDecimal.mode.
  2844. *
  2845. * A limit of 0, the default, means no upper limit.
  2846. *
  2847. * The limit specified by this method takes less priority over any limit
  2848. * specified to instance methods such as ceil, floor, truncate, or round.
  2849. */
  2850. static VALUE
  2851. BigDecimal_limit(int argc, VALUE *argv, VALUE self)
  2852. {
  2853. VALUE nFig;
  2854. VALUE nCur = SIZET2NUM(VpGetPrecLimit());
  2855. if (rb_scan_args(argc, argv, "01", &nFig) == 1) {
  2856. int nf;
  2857. if (NIL_P(nFig)) return nCur;
  2858. nf = NUM2INT(nFig);
  2859. if (nf < 0) {
  2860. rb_raise(rb_eArgError, "argument must be positive");
  2861. }
  2862. VpSetPrecLimit(nf);
  2863. }
  2864. return nCur;
  2865. }
  2866. /* Returns the sign of the value.
  2867. *
  2868. * Returns a positive value if > 0, a negative value if < 0, and a
  2869. * zero if == 0.
  2870. *
  2871. * The specific value returned indicates the type and sign of the BigDecimal,
  2872. * as follows:
  2873. *
  2874. * BigDecimal::SIGN_NaN:: value is Not a Number
  2875. * BigDecimal::SIGN_POSITIVE_ZERO:: value is +0
  2876. * BigDecimal::SIGN_NEGATIVE_ZERO:: value is -0
  2877. * BigDecimal::SIGN_POSITIVE_INFINITE:: value is +Infinity
  2878. * BigDecimal::SIGN_NEGATIVE_INFINITE:: value is -Infinity
  2879. * BigDecimal::SIGN_POSITIVE_FINITE:: value is positive
  2880. * BigDecimal::SIGN_NEGATIVE_FINITE:: value is negative
  2881. */
  2882. static VALUE
  2883. BigDecimal_sign(VALUE self)
  2884. { /* sign */
  2885. int s = GetVpValue(self, 1)->sign;
  2886. return INT2FIX(s);
  2887. }
  2888. /*
  2889. * call-seq: BigDecimal.save_exception_mode { ... }
  2890. *
  2891. * Execute the provided block, but preserve the exception mode
  2892. *
  2893. * BigDecimal.save_exception_mode do
  2894. * BigDecimal.mode(BigDecimal::EXCEPTION_OVERFLOW, false)
  2895. * BigDecimal.mode(BigDecimal::EXCEPTION_NaN, false)
  2896. *
  2897. * BigDecimal(BigDecimal('Infinity'))
  2898. * BigDecimal(BigDecimal('-Infinity'))
  2899. * BigDecimal(BigDecimal('NaN'))
  2900. * end
  2901. *
  2902. * For use with the BigDecimal::EXCEPTION_*
  2903. *
  2904. * See BigDecimal.mode
  2905. */
  2906. static VALUE
  2907. BigDecimal_save_exception_mode(VALUE self)
  2908. {
  2909. unsigned short const exception_mode = VpGetException();
  2910. int state;
  2911. VALUE ret = rb_protect(rb_yield, Qnil, &state);
  2912. VpSetException(exception_mode);
  2913. if (state) rb_jump_tag(state);
  2914. return ret;
  2915. }
  2916. /*
  2917. * call-seq: BigDecimal.save_rounding_mode { ... }
  2918. *
  2919. * Execute the provided block, but preserve the rounding mode
  2920. *
  2921. * BigDecimal.save_rounding_mode do
  2922. * BigDecimal.mode(BigDecimal::ROUND_MODE, :up)
  2923. * puts BigDecimal.mode(BigDecimal::ROUND_MODE)
  2924. * end
  2925. *
  2926. * For use with the BigDecimal::ROUND_*
  2927. *
  2928. * See BigDecimal.mode
  2929. */
  2930. static VALUE
  2931. BigDecimal_save_rounding_mode(VALUE self)
  2932. {
  2933. unsigned short const round_mode = VpGetRoundMode();
  2934. int state;
  2935. VALUE ret = rb_protect(rb_yield, Qnil, &state);
  2936. VpSetRoundMode(round_mode);
  2937. if (state) rb_jump_tag(state);
  2938. return ret;
  2939. }
  2940. /*
  2941. * call-seq: BigDecimal.save_limit { ... }
  2942. *
  2943. * Execute the provided block, but preserve the precision limit
  2944. *
  2945. * BigDecimal.limit(100)
  2946. * puts BigDecimal.limit
  2947. * BigDecimal.save_limit do
  2948. * BigDecimal.limit(200)
  2949. * puts BigDecimal.limit
  2950. * end
  2951. * puts BigDecimal.limit
  2952. *
  2953. */
  2954. static VALUE
  2955. BigDecimal_save_limit(VALUE self)
  2956. {
  2957. size_t const limit = VpGetPrecLimit();
  2958. int state;
  2959. VALUE ret = rb_protect(rb_yield, Qnil, &state);
  2960. VpSetPrecLimit(limit);
  2961. if (state) rb_jump_tag(state);
  2962. return ret;
  2963. }
  2964. /* call-seq:
  2965. * BigMath.exp(decimal, numeric) -> BigDecimal
  2966. *
  2967. * Computes the value of e (the base of natural logarithms) raised to the
  2968. * power of +decimal+, to the specified number of digits of precision.
  2969. *
  2970. * If +decimal+ is infinity, returns Infinity.
  2971. *
  2972. * If +decimal+ is NaN, returns NaN.
  2973. */
  2974. static VALUE
  2975. BigMath_s_exp(VALUE klass, VALUE x, VALUE vprec)
  2976. {
  2977. ssize_t prec, n, i;
  2978. Real* vx = NULL;
  2979. VALUE one, d, y;
  2980. int negative = 0;
  2981. int infinite = 0;
  2982. int nan = 0;
  2983. double flo;
  2984. prec = NUM2SSIZET(vprec);
  2985. if (prec <= 0) {
  2986. rb_raise(rb_eArgError, "Zero or negative precision for exp");
  2987. }
  2988. /* TODO: the following switch statement is almost same as one in the
  2989. * BigDecimalCmp function. */
  2990. switch (TYPE(x)) {
  2991. case T_DATA:
  2992. if (!is_kind_of_BigDecimal(x)) break;
  2993. vx = DATA_PTR(x);
  2994. negative = BIGDECIMAL_NEGATIVE_P(vx);
  2995. infinite = VpIsPosInf(vx) || VpIsNegInf(vx);
  2996. nan = VpIsNaN(vx);
  2997. break;
  2998. case T_FIXNUM:
  2999. /* fall through */
  3000. case T_BIGNUM:
  3001. vx = GetVpValue(x, 0);
  3002. break;
  3003. case T_FLOAT:
  3004. flo = RFLOAT_VALUE(x);
  3005. negative = flo < 0;
  3006. infinite = isinf(flo);
  3007. nan = isnan(flo);
  3008. if (!infinite && !nan) {
  3009. vx = GetVpValueWithPrec(x, 0, 0);
  3010. }
  3011. break;
  3012. case T_RATIONAL:
  3013. vx = GetVpValueWithPrec(x, prec, 0);
  3014. break;
  3015. default:
  3016. break;
  3017. }
  3018. if (infinite) {
  3019. if (negative) {
  3020. return VpCheckGetValue(GetVpValueWithPrec(INT2FIX(0), prec, 1));
  3021. }
  3022. else {
  3023. Real* vy;
  3024. vy = VpCreateRbObject(prec, "#0", true);
  3025. VpSetInf(vy, VP_SIGN_POSITIVE_INFINITE);
  3026. RB_GC_GUARD(vy->obj);
  3027. return VpCheckGetValue(vy);
  3028. }
  3029. }
  3030. else if (nan) {
  3031. Real* vy;
  3032. vy = VpCreateRbObject(prec, "#0", true);
  3033. VpSetNaN(vy);
  3034. RB_GC_GUARD(vy->obj);
  3035. return VpCheckGetValue(vy);
  3036. }
  3037. else if (vx == NULL) {
  3038. cannot_be_coerced_into_BigDecimal(rb_eArgError, x);
  3039. }
  3040. x = vx->obj;
  3041. n = prec + BIGDECIMAL_DOUBLE_FIGURES;
  3042. negative = BIGDECIMAL_NEGATIVE_P(vx);
  3043. if (negative) {
  3044. VALUE x_zero = INT2NUM(1);
  3045. VALUE x_copy = f_BigDecimal(1, &x_zero, klass);
  3046. x = BigDecimal_initialize_copy(x_copy, x);
  3047. vx = DATA_PTR(x);
  3048. VpSetSign(vx, 1);
  3049. }
  3050. one = VpCheckGetValue(VpCreateRbObject(1, "1", true));
  3051. y = one;
  3052. d = y;
  3053. i = 1;
  3054. while (!VpIsZero((Real*)DATA_PTR(d))) {
  3055. SIGNED_VALUE const ey = VpExponent10(DATA_PTR(y));
  3056. SIGNED_VALUE const ed = VpExponent10(DATA_PTR(d));
  3057. ssize_t m = n - vabs(ey - ed);
  3058. rb_thread_check_ints();
  3059. if (m <= 0) {
  3060. break;
  3061. }
  3062. else if ((size_t)m < BIGDECIMAL_DOUBLE_FIGURES) {
  3063. m = BIGDECIMAL_DOUBLE_FIGURES;
  3064. }
  3065. d = BigDecimal_mult(d, x); /* d <- d * x */
  3066. d = BigDecimal_div2(d, SSIZET2NUM(i), SSIZET2NUM(m)); /* d <- d / i */
  3067. y = BigDecimal_add(y, d); /* y <- y + d */
  3068. ++i; /* i <- i + 1 */
  3069. }
  3070. if (negative) {
  3071. return BigDecimal_div2(one, y, vprec);
  3072. }
  3073. else {
  3074. vprec = SSIZET2NUM(prec - VpExponent10(DATA_PTR(y)));
  3075. return BigDecimal_round(1, &vprec, y);
  3076. }
  3077. RB_GC_GUARD(one);
  3078. RB_GC_GUARD(x);
  3079. RB_GC_GUARD(y);
  3080. RB_GC_GUARD(d);
  3081. }
  3082. /* call-seq:
  3083. * BigMath.log(decimal, numeric) -> BigDecimal
  3084. *
  3085. * Computes the natural logarithm of +decimal+ to the specified number of
  3086. * digits of precision, +numeric+.
  3087. *
  3088. * If +decimal+ is zero or negative, raises Math::DomainError.
  3089. *
  3090. * If +decimal+ is positive infinity, returns Infinity.
  3091. *
  3092. * If +decimal+ is NaN, returns NaN.
  3093. */
  3094. static VALUE
  3095. BigMath_s_log(VALUE klass, VALUE x, VALUE vprec)
  3096. {
  3097. ssize_t prec, n, i;
  3098. SIGNED_VALUE expo;
  3099. Real* vx = NULL;
  3100. VALUE vn, one, two, w, x2, y, d;
  3101. int zero = 0;
  3102. int negative = 0;
  3103. int infinite = 0;
  3104. int nan = 0;
  3105. double flo;
  3106. long fix;
  3107. if (!is_integer(vprec)) {
  3108. rb_raise(rb_eArgError, "precision must be an Integer");
  3109. }
  3110. prec = NUM2SSIZET(vprec);
  3111. if (prec <= 0) {
  3112. rb_raise(rb_eArgError, "Zero or negative precision for exp");
  3113. }
  3114. /* TODO: the following switch statement is almost same as one in the
  3115. * BigDecimalCmp function. */
  3116. switch (TYPE(x)) {
  3117. case T_DATA:
  3118. if (!is_kind_of_BigDecimal(x)) break;
  3119. vx = DATA_PTR(x);
  3120. zero = VpIsZero(vx);
  3121. negative = BIGDECIMAL_NEGATIVE_P(vx);
  3122. infinite = VpIsPosInf(vx) || VpIsNegInf(vx);
  3123. nan = VpIsNaN(vx);
  3124. break;
  3125. case T_FIXNUM:
  3126. fix = FIX2LONG(x);
  3127. zero = fix == 0;
  3128. negative = fix < 0;
  3129. goto get_vp_value;
  3130. case T_BIGNUM:
  3131. i = FIX2INT(rb_big_cmp(x, INT2FIX(0)));
  3132. zero = i == 0;
  3133. negative = i < 0;
  3134. get_vp_value:
  3135. if (zero || negative) break;
  3136. vx = GetVpValue(x, 0);
  3137. break;
  3138. case T_FLOAT:
  3139. flo = RFLOAT_VALUE(x);
  3140. zero = flo == 0;
  3141. negative = flo < 0;
  3142. infinite = isinf(flo);
  3143. nan = isnan(flo);
  3144. if (!zero && !negative && !infinite && !nan) {
  3145. vx = GetVpValueWithPrec(x, 0, 1);
  3146. }
  3147. break;
  3148. case T_RATIONAL:
  3149. zero = RRATIONAL_ZERO_P(x);
  3150. negative = RRATIONAL_NEGATIVE_P(x);
  3151. if (zero || negative) break;
  3152. vx = GetVpValueWithPrec(x, prec, 1);
  3153. break;
  3154. case T_COMPLEX:
  3155. rb_raise(rb_eMathDomainError,
  3156. "Complex argument for BigMath.log");
  3157. default:
  3158. break;
  3159. }
  3160. if (infinite && !negative) {
  3161. Real* vy;
  3162. vy = VpCreateRbObject(prec, "#0", true);
  3163. RB_GC_GUARD(vy->obj);
  3164. VpSetInf(vy, VP_SIGN_POSITIVE_INFINITE);
  3165. return VpCheckGetValue(vy);
  3166. }
  3167. else if (nan) {
  3168. Real* vy;
  3169. vy = VpCreateRbObject(prec, "#0", true);
  3170. RB_GC_GUARD(vy->obj);
  3171. VpSetNaN(vy);
  3172. return VpCheckGetValue(vy);
  3173. }
  3174. else if (zero || negative) {
  3175. rb_raise(rb_eMathDomainError,
  3176. "Zero or negative argument for log");
  3177. }
  3178. else if (vx == NULL) {
  3179. cannot_be_coerced_into_BigDecimal(rb_eArgError, x);
  3180. }
  3181. x = VpCheckGetValue(vx);
  3182. RB_GC_GUARD(one) = VpCheckGetValue(VpCreateRbObject(1, "1", true));
  3183. RB_GC_GUARD(two) = VpCheckGetValue(VpCreateRbObject(1, "2", true));
  3184. n = prec + BIGDECIMAL_DOUBLE_FIGURES;
  3185. RB_GC_GUARD(vn) = SSIZET2NUM(n);
  3186. expo = VpExponent10(vx);
  3187. if (expo < 0 || expo >= 3) {
  3188. char buf[DECIMAL_SIZE_OF_BITS(SIZEOF_VALUE * CHAR_BIT) + 4];
  3189. snprintf(buf, sizeof(buf), "1E%"PRIdVALUE, -expo);
  3190. x = BigDecimal_mult2(x, VpCheckGetValue(VpCreateRbObject(1, buf, true)), vn);
  3191. }
  3192. else {
  3193. expo = 0;
  3194. }
  3195. w = BigDecimal_sub(x, one);
  3196. x = BigDecimal_div2(w, BigDecimal_add(x, one), vn);
  3197. RB_GC_GUARD(x2) = BigDecimal_mult2(x, x, vn);
  3198. RB_GC_GUARD(y) = x;
  3199. RB_GC_GUARD(d) = y;
  3200. i = 1;
  3201. while (!VpIsZero((Real*)DATA_PTR(d))) {
  3202. SIGNED_VALUE const ey = VpExponent10(DATA_PTR(y));
  3203. SIGNED_VALUE const ed = VpExponent10(DATA_PTR(d));
  3204. ssize_t m = n - vabs(ey - ed);
  3205. if (m <= 0) {
  3206. break;
  3207. }
  3208. else if ((size_t)m < BIGDECIMAL_DOUBLE_FIGURES) {
  3209. m = BIGDECIMAL_DOUBLE_FIGURES;
  3210. }
  3211. x = BigDecimal_mult2(x2, x, vn);
  3212. i += 2;
  3213. d = BigDecimal_div2(x, SSIZET2NUM(i), SSIZET2NUM(m));
  3214. y = BigDecimal_add(y, d);
  3215. }
  3216. y = BigDecimal_mult(y, two);
  3217. if (expo != 0) {
  3218. VALUE log10, vexpo, dy;
  3219. log10 = BigMath_s_log(klass, INT2FIX(10), vprec);
  3220. vexpo = VpCheckGetValue(GetVpValue(SSIZET2NUM(expo), 1));
  3221. dy = BigDecimal_mult(log10, vexpo);
  3222. y = BigDecimal_add(y, dy);
  3223. }
  3224. return y;
  3225. }
  3226. static VALUE BIGDECIMAL_NAN = Qnil;
  3227. static VALUE
  3228. BigDecimal_nan(void)
  3229. {
  3230. return BIGDECIMAL_NAN;
  3231. }
  3232. static VALUE BIGDECIMAL_POSITIVE_INFINITY = Qnil;
  3233. static VALUE
  3234. BigDecimal_positive_infinity(void)
  3235. {
  3236. return BIGDECIMAL_POSITIVE_INFINITY;
  3237. }
  3238. static VALUE BIGDECIMAL_NEGATIVE_INFINITY = Qnil;
  3239. static VALUE
  3240. BigDecimal_negative_infinity(void)
  3241. {
  3242. return BIGDECIMAL_NEGATIVE_INFINITY;
  3243. }
  3244. static VALUE BIGDECIMAL_POSITIVE_ZERO = Qnil;
  3245. static VALUE
  3246. BigDecimal_positive_zero(void)
  3247. {
  3248. return BIGDECIMAL_POSITIVE_ZERO;
  3249. }
  3250. static VALUE BIGDECIMAL_NEGATIVE_ZERO = Qnil;
  3251. static VALUE
  3252. BigDecimal_negative_zero(void)
  3253. {
  3254. return BIGDECIMAL_NEGATIVE_ZERO;
  3255. }
  3256. /* Document-class: BigDecimal
  3257. * BigDecimal provides arbitrary-precision floating point decimal arithmetic.
  3258. *
  3259. * == Introduction
  3260. *
  3261. * Ruby provides built-in support for arbitrary precision integer arithmetic.
  3262. *
  3263. * For example:
  3264. *
  3265. * 42**13 #=> 1265437718438866624512
  3266. *
  3267. * BigDecimal provides similar support for very large or very accurate floating
  3268. * point numbers.
  3269. *
  3270. * Decimal arithmetic is also useful for general calculation, because it
  3271. * provides the correct answers people expect--whereas normal binary floating
  3272. * point arithmetic often introduces subtle errors because of the conversion
  3273. * between base 10 and base 2.
  3274. *
  3275. * For example, try:
  3276. *
  3277. * sum = 0
  3278. * 10_000.times do
  3279. * sum = sum + 0.0001
  3280. * end
  3281. * print sum #=> 0.9999999999999062
  3282. *
  3283. * and contrast with the output from:
  3284. *
  3285. * require 'bigdecimal'
  3286. *
  3287. * sum = BigDecimal("0")
  3288. * 10_000.times do
  3289. * sum = sum + BigDecimal("0.0001")
  3290. * end
  3291. * print sum #=> 0.1E1
  3292. *
  3293. * Similarly:
  3294. *
  3295. * (BigDecimal("1.2") - BigDecimal("1.0")) == BigDecimal("0.2") #=> true
  3296. *
  3297. * (1.2 - 1.0) == 0.2 #=> false
  3298. *
  3299. * == Special features of accurate decimal arithmetic
  3300. *
  3301. * Because BigDecimal is more accurate than normal binary floating point
  3302. * arithmetic, it requires some special values.
  3303. *
  3304. * === Infinity
  3305. *
  3306. * BigDecimal sometimes needs to return infinity, for example if you divide
  3307. * a value by zero.
  3308. *
  3309. * BigDecimal("1.0") / BigDecimal("0.0") #=> Infinity
  3310. * BigDecimal("-1.0") / BigDecimal("0.0") #=> -Infinity
  3311. *
  3312. * You can represent infinite numbers to BigDecimal using the strings
  3313. * <code>'Infinity'</code>, <code>'+Infinity'</code> and
  3314. * <code>'-Infinity'</code> (case-sensitive)
  3315. *
  3316. * === Not a Number
  3317. *
  3318. * When a computation results in an undefined value, the special value +NaN+
  3319. * (for 'not a number') is returned.
  3320. *
  3321. * Example:
  3322. *
  3323. * BigDecimal("0.0") / BigDecimal("0.0") #=> NaN
  3324. *
  3325. * You can also create undefined values.
  3326. *
  3327. * NaN is never considered to be the same as any other value, even NaN itself:
  3328. *
  3329. * n = BigDecimal('NaN')
  3330. * n == 0.0 #=> false
  3331. * n == n #=> false
  3332. *
  3333. * === Positive and negative zero
  3334. *
  3335. * If a computation results in a value which is too small to be represented as
  3336. * a BigDecimal within the currently specified limits of precision, zero must
  3337. * be returned.
  3338. *
  3339. * If the value which is too small to be represented is negative, a BigDecimal
  3340. * value of negative zero is returned.
  3341. *
  3342. * BigDecimal("1.0") / BigDecimal("-Infinity") #=> -0.0
  3343. *
  3344. * If the value is positive, a value of positive zero is returned.
  3345. *
  3346. * BigDecimal("1.0") / BigDecimal("Infinity") #=> 0.0
  3347. *
  3348. * (See BigDecimal.mode for how to specify limits of precision.)
  3349. *
  3350. * Note that +-0.0+ and +0.0+ are considered to be the same for the purposes of
  3351. * comparison.
  3352. *
  3353. * Note also that in mathematics, there is no particular concept of negative
  3354. * or positive zero; true mathematical zero has no sign.
  3355. *
  3356. * == bigdecimal/util
  3357. *
  3358. * When you require +bigdecimal/util+, the #to_d method will be
  3359. * available on BigDecimal and the native Integer, Float, Rational,
  3360. * and String classes:
  3361. *
  3362. * require 'bigdecimal/util'
  3363. *
  3364. * 42.to_d # => 0.42e2
  3365. * 0.5.to_d # => 0.5e0
  3366. * (2/3r).to_d(3) # => 0.667e0
  3367. * "0.5".to_d # => 0.5e0
  3368. *
  3369. * == License
  3370. *
  3371. * Copyright (C) 2002 by Shigeo Kobayashi <shigeo@tinyforest.gr.jp>.
  3372. *
  3373. * BigDecimal is released under the Ruby and 2-clause BSD licenses.
  3374. * See LICENSE.txt for details.
  3375. *
  3376. * Maintained by mrkn <mrkn@mrkn.jp> and ruby-core members.
  3377. *
  3378. * Documented by zzak <zachary@zacharyscott.net>, mathew <meta@pobox.com>, and
  3379. * many other contributors.
  3380. */
  3381. void
  3382. Init_bigdecimal(void)
  3383. {
  3384. #ifdef HAVE_RB_EXT_RACTOR_SAFE
  3385. rb_ext_ractor_safe(true);
  3386. #endif
  3387. VALUE arg;
  3388. id_BigDecimal_exception_mode = rb_intern_const("BigDecimal.exception_mode");
  3389. id_BigDecimal_rounding_mode = rb_intern_const("BigDecimal.rounding_mode");
  3390. id_BigDecimal_precision_limit = rb_intern_const("BigDecimal.precision_limit");
  3391. /* Initialize VP routines */
  3392. VpInit(0UL);
  3393. /* Class and method registration */
  3394. rb_cBigDecimal = rb_define_class("BigDecimal", rb_cNumeric);
  3395. /* Global function */
  3396. rb_define_global_function("BigDecimal", f_BigDecimal, -1);
  3397. /* Class methods */
  3398. rb_undef_alloc_func(rb_cBigDecimal);
  3399. rb_undef_method(CLASS_OF(rb_cBigDecimal), "new");
  3400. rb_define_singleton_method(rb_cBigDecimal, "interpret_loosely", BigDecimal_s_interpret_loosely, 1);
  3401. rb_define_singleton_method(rb_cBigDecimal, "mode", BigDecimal_mode, -1);
  3402. rb_define_singleton_method(rb_cBigDecimal, "limit", BigDecimal_limit, -1);
  3403. rb_define_singleton_method(rb_cBigDecimal, "double_fig", BigDecimal_double_fig, 0);
  3404. rb_define_singleton_method(rb_cBigDecimal, "_load", BigDecimal_load, 1);
  3405. rb_define_singleton_method(rb_cBigDecimal, "save_exception_mode", BigDecimal_save_exception_mode, 0);
  3406. rb_define_singleton_method(rb_cBigDecimal, "save_rounding_mode", BigDecimal_save_rounding_mode, 0);
  3407. rb_define_singleton_method(rb_cBigDecimal, "save_limit", BigDecimal_save_limit, 0);
  3408. /* Constants definition */
  3409. #ifndef RUBY_BIGDECIMAL_VERSION
  3410. # error RUBY_BIGDECIMAL_VERSION is not defined
  3411. #endif
  3412. /*
  3413. * The version of bigdecimal library
  3414. */
  3415. rb_define_const(rb_cBigDecimal, "VERSION", rb_str_new2(RUBY_BIGDECIMAL_VERSION));
  3416. /*
  3417. * Base value used in internal calculations. On a 32 bit system, BASE
  3418. * is 10000, indicating that calculation is done in groups of 4 digits.
  3419. * (If it were larger, BASE**2 wouldn't fit in 32 bits, so you couldn't
  3420. * guarantee that two groups could always be multiplied together without
  3421. * overflow.)
  3422. */
  3423. rb_define_const(rb_cBigDecimal, "BASE", INT2FIX((SIGNED_VALUE)VpBaseVal()));
  3424. /* Exceptions */
  3425. /*
  3426. * 0xff: Determines whether overflow, underflow or zero divide result in
  3427. * an exception being thrown. See BigDecimal.mode.
  3428. */
  3429. rb_define_const(rb_cBigDecimal, "EXCEPTION_ALL", INT2FIX(VP_EXCEPTION_ALL));
  3430. /*
  3431. * 0x02: Determines what happens when the result of a computation is not a
  3432. * number (NaN). See BigDecimal.mode.
  3433. */
  3434. rb_define_const(rb_cBigDecimal, "EXCEPTION_NaN", INT2FIX(VP_EXCEPTION_NaN));
  3435. /*
  3436. * 0x01: Determines what happens when the result of a computation is
  3437. * infinity. See BigDecimal.mode.
  3438. */
  3439. rb_define_const(rb_cBigDecimal, "EXCEPTION_INFINITY", INT2FIX(VP_EXCEPTION_INFINITY));
  3440. /*
  3441. * 0x04: Determines what happens when the result of a computation is an
  3442. * underflow (a result too small to be represented). See BigDecimal.mode.
  3443. */
  3444. rb_define_const(rb_cBigDecimal, "EXCEPTION_UNDERFLOW", INT2FIX(VP_EXCEPTION_UNDERFLOW));
  3445. /*
  3446. * 0x01: Determines what happens when the result of a computation is an
  3447. * overflow (a result too large to be represented). See BigDecimal.mode.
  3448. */
  3449. rb_define_const(rb_cBigDecimal, "EXCEPTION_OVERFLOW", INT2FIX(VP_EXCEPTION_OVERFLOW));
  3450. /*
  3451. * 0x10: Determines what happens when a division by zero is performed.
  3452. * See BigDecimal.mode.
  3453. */
  3454. rb_define_const(rb_cBigDecimal, "EXCEPTION_ZERODIVIDE", INT2FIX(VP_EXCEPTION_ZERODIVIDE));
  3455. /*
  3456. * 0x100: Determines what happens when a result must be rounded in order to
  3457. * fit in the appropriate number of significant digits. See
  3458. * BigDecimal.mode.
  3459. */
  3460. rb_define_const(rb_cBigDecimal, "ROUND_MODE", INT2FIX(VP_ROUND_MODE));
  3461. /* 1: Indicates that values should be rounded away from zero. See
  3462. * BigDecimal.mode.
  3463. */
  3464. rb_define_const(rb_cBigDecimal, "ROUND_UP", INT2FIX(VP_ROUND_UP));
  3465. /* 2: Indicates that values should be rounded towards zero. See
  3466. * BigDecimal.mode.
  3467. */
  3468. rb_define_const(rb_cBigDecimal, "ROUND_DOWN", INT2FIX(VP_ROUND_DOWN));
  3469. /* 3: Indicates that digits >= 5 should be rounded up, others rounded down.
  3470. * See BigDecimal.mode. */
  3471. rb_define_const(rb_cBigDecimal, "ROUND_HALF_UP", INT2FIX(VP_ROUND_HALF_UP));
  3472. /* 4: Indicates that digits >= 6 should be rounded up, others rounded down.
  3473. * See BigDecimal.mode.
  3474. */
  3475. rb_define_const(rb_cBigDecimal, "ROUND_HALF_DOWN", INT2FIX(VP_ROUND_HALF_DOWN));
  3476. /* 5: Round towards +Infinity. See BigDecimal.mode. */
  3477. rb_define_const(rb_cBigDecimal, "ROUND_CEILING", INT2FIX(VP_ROUND_CEIL));
  3478. /* 6: Round towards -Infinity. See BigDecimal.mode. */
  3479. rb_define_const(rb_cBigDecimal, "ROUND_FLOOR", INT2FIX(VP_ROUND_FLOOR));
  3480. /* 7: Round towards the even neighbor. See BigDecimal.mode. */
  3481. rb_define_const(rb_cBigDecimal, "ROUND_HALF_EVEN", INT2FIX(VP_ROUND_HALF_EVEN));
  3482. /* 0: Indicates that a value is not a number. See BigDecimal.sign. */
  3483. rb_define_const(rb_cBigDecimal, "SIGN_NaN", INT2FIX(VP_SIGN_NaN));
  3484. /* 1: Indicates that a value is +0. See BigDecimal.sign. */
  3485. rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_ZERO", INT2FIX(VP_SIGN_POSITIVE_ZERO));
  3486. /* -1: Indicates that a value is -0. See BigDecimal.sign. */
  3487. rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_ZERO", INT2FIX(VP_SIGN_NEGATIVE_ZERO));
  3488. /* 2: Indicates that a value is positive and finite. See BigDecimal.sign. */
  3489. rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_FINITE", INT2FIX(VP_SIGN_POSITIVE_FINITE));
  3490. /* -2: Indicates that a value is negative and finite. See BigDecimal.sign. */
  3491. rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_FINITE", INT2FIX(VP_SIGN_NEGATIVE_FINITE));
  3492. /* 3: Indicates that a value is positive and infinite. See BigDecimal.sign. */
  3493. rb_define_const(rb_cBigDecimal, "SIGN_POSITIVE_INFINITE", INT2FIX(VP_SIGN_POSITIVE_INFINITE));
  3494. /* -3: Indicates that a value is negative and infinite. See BigDecimal.sign. */
  3495. rb_define_const(rb_cBigDecimal, "SIGN_NEGATIVE_INFINITE", INT2FIX(VP_SIGN_NEGATIVE_INFINITE));
  3496. /* Positive zero value. */
  3497. arg = rb_str_new2("+0");
  3498. BIGDECIMAL_POSITIVE_ZERO = f_BigDecimal(1, &arg, rb_cBigDecimal);
  3499. rb_gc_register_mark_object(BIGDECIMAL_POSITIVE_ZERO);
  3500. /* Negative zero value. */
  3501. arg = rb_str_new2("-0");
  3502. BIGDECIMAL_NEGATIVE_ZERO = f_BigDecimal(1, &arg, rb_cBigDecimal);
  3503. rb_gc_register_mark_object(BIGDECIMAL_NEGATIVE_ZERO);
  3504. /* Positive infinity value. */
  3505. arg = rb_str_new2("+Infinity");
  3506. BIGDECIMAL_POSITIVE_INFINITY = f_BigDecimal(1, &arg, rb_cBigDecimal);
  3507. rb_gc_register_mark_object(BIGDECIMAL_POSITIVE_INFINITY);
  3508. /* Negative infinity value. */
  3509. arg = rb_str_new2("-Infinity");
  3510. BIGDECIMAL_NEGATIVE_INFINITY = f_BigDecimal(1, &arg, rb_cBigDecimal);
  3511. rb_gc_register_mark_object(BIGDECIMAL_NEGATIVE_INFINITY);
  3512. /* 'Not a Number' value. */
  3513. arg = rb_str_new2("NaN");
  3514. BIGDECIMAL_NAN = f_BigDecimal(1, &arg, rb_cBigDecimal);
  3515. rb_gc_register_mark_object(BIGDECIMAL_NAN);
  3516. /* Special value constants */
  3517. rb_define_const(rb_cBigDecimal, "INFINITY", BIGDECIMAL_POSITIVE_INFINITY);
  3518. rb_define_const(rb_cBigDecimal, "NAN", BIGDECIMAL_NAN);
  3519. /* instance methods */
  3520. rb_define_method(rb_cBigDecimal, "precs", BigDecimal_prec, 0);
  3521. rb_define_method(rb_cBigDecimal, "precision", BigDecimal_precision, 0);
  3522. rb_define_method(rb_cBigDecimal, "n_significant_digits", BigDecimal_n_significant_digits, 0);
  3523. rb_define_method(rb_cBigDecimal, "add", BigDecimal_add2, 2);
  3524. rb_define_method(rb_cBigDecimal, "sub", BigDecimal_sub2, 2);
  3525. rb_define_method(rb_cBigDecimal, "mult", BigDecimal_mult2, 2);
  3526. rb_define_method(rb_cBigDecimal, "div", BigDecimal_div3, -1);
  3527. rb_define_method(rb_cBigDecimal, "hash", BigDecimal_hash, 0);
  3528. rb_define_method(rb_cBigDecimal, "to_s", BigDecimal_to_s, -1);
  3529. rb_define_method(rb_cBigDecimal, "to_i", BigDecimal_to_i, 0);
  3530. rb_define_method(rb_cBigDecimal, "to_int", BigDecimal_to_i, 0);
  3531. rb_define_method(rb_cBigDecimal, "to_r", BigDecimal_to_r, 0);
  3532. rb_define_method(rb_cBigDecimal, "split", BigDecimal_split, 0);
  3533. rb_define_method(rb_cBigDecimal, "+", BigDecimal_add, 1);
  3534. rb_define_method(rb_cBigDecimal, "-", BigDecimal_sub, 1);
  3535. rb_define_method(rb_cBigDecimal, "+@", BigDecimal_uplus, 0);
  3536. rb_define_method(rb_cBigDecimal, "-@", BigDecimal_neg, 0);
  3537. rb_define_method(rb_cBigDecimal, "*", BigDecimal_mult, 1);
  3538. rb_define_method(rb_cBigDecimal, "/", BigDecimal_div, 1);
  3539. rb_define_method(rb_cBigDecimal, "quo", BigDecimal_div, 1);
  3540. rb_define_method(rb_cBigDecimal, "%", BigDecimal_mod, 1);
  3541. rb_define_method(rb_cBigDecimal, "modulo", BigDecimal_mod, 1);
  3542. rb_define_method(rb_cBigDecimal, "remainder", BigDecimal_remainder, 1);
  3543. rb_define_method(rb_cBigDecimal, "divmod", BigDecimal_divmod, 1);
  3544. rb_define_method(rb_cBigDecimal, "clone", BigDecimal_clone, 0);
  3545. rb_define_method(rb_cBigDecimal, "dup", BigDecimal_clone, 0);
  3546. rb_define_method(rb_cBigDecimal, "to_f", BigDecimal_to_f, 0);
  3547. rb_define_method(rb_cBigDecimal, "abs", BigDecimal_abs, 0);
  3548. rb_define_method(rb_cBigDecimal, "sqrt", BigDecimal_sqrt, 1);
  3549. rb_define_method(rb_cBigDecimal, "fix", BigDecimal_fix, 0);
  3550. rb_define_method(rb_cBigDecimal, "round", BigDecimal_round, -1);
  3551. rb_define_method(rb_cBigDecimal, "frac", BigDecimal_frac, 0);
  3552. rb_define_method(rb_cBigDecimal, "floor", BigDecimal_floor, -1);
  3553. rb_define_method(rb_cBigDecimal, "ceil", BigDecimal_ceil, -1);
  3554. rb_define_method(rb_cBigDecimal, "power", BigDecimal_power, -1);
  3555. rb_define_method(rb_cBigDecimal, "**", BigDecimal_power_op, 1);
  3556. rb_define_method(rb_cBigDecimal, "<=>", BigDecimal_comp, 1);
  3557. rb_define_method(rb_cBigDecimal, "==", BigDecimal_eq, 1);
  3558. rb_define_method(rb_cBigDecimal, "===", BigDecimal_eq, 1);
  3559. rb_define_method(rb_cBigDecimal, "eql?", BigDecimal_eq, 1);
  3560. rb_define_method(rb_cBigDecimal, "<", BigDecimal_lt, 1);
  3561. rb_define_method(rb_cBigDecimal, "<=", BigDecimal_le, 1);
  3562. rb_define_method(rb_cBigDecimal, ">", BigDecimal_gt, 1);
  3563. rb_define_method(rb_cBigDecimal, ">=", BigDecimal_ge, 1);
  3564. rb_define_method(rb_cBigDecimal, "zero?", BigDecimal_zero, 0);
  3565. rb_define_method(rb_cBigDecimal, "nonzero?", BigDecimal_nonzero, 0);
  3566. rb_define_method(rb_cBigDecimal, "coerce", BigDecimal_coerce, 1);
  3567. rb_define_method(rb_cBigDecimal, "inspect", BigDecimal_inspect, 0);
  3568. rb_define_method(rb_cBigDecimal, "exponent", BigDecimal_exponent, 0);
  3569. rb_define_method(rb_cBigDecimal, "sign", BigDecimal_sign, 0);
  3570. rb_define_method(rb_cBigDecimal, "nan?", BigDecimal_IsNaN, 0);
  3571. rb_define_method(rb_cBigDecimal, "infinite?", BigDecimal_IsInfinite, 0);
  3572. rb_define_method(rb_cBigDecimal, "finite?", BigDecimal_IsFinite, 0);
  3573. rb_define_method(rb_cBigDecimal, "truncate", BigDecimal_truncate, -1);
  3574. rb_define_method(rb_cBigDecimal, "_dump", BigDecimal_dump, -1);
  3575. rb_mBigMath = rb_define_module("BigMath");
  3576. rb_define_singleton_method(rb_mBigMath, "exp", BigMath_s_exp, 2);
  3577. rb_define_singleton_method(rb_mBigMath, "log", BigMath_s_log, 2);
  3578. id_up = rb_intern_const("up");
  3579. id_down = rb_intern_const("down");
  3580. id_truncate = rb_intern_const("truncate");
  3581. id_half_up = rb_intern_const("half_up");
  3582. id_default = rb_intern_const("default");
  3583. id_half_down = rb_intern_const("half_down");
  3584. id_half_even = rb_intern_const("half_even");
  3585. id_banker = rb_intern_const("banker");
  3586. id_ceiling = rb_intern_const("ceiling");
  3587. id_ceil = rb_intern_const("ceil");
  3588. id_floor = rb_intern_const("floor");
  3589. id_to_r = rb_intern_const("to_r");
  3590. id_eq = rb_intern_const("==");
  3591. id_half = rb_intern_const("half");
  3592. }
  3593. /*
  3594. *
  3595. * ============================================================================
  3596. *
  3597. * vp_ routines begin from here.
  3598. *
  3599. * ============================================================================
  3600. *
  3601. */
  3602. #ifdef BIGDECIMAL_DEBUG
  3603. static int gfDebug = 1; /* Debug switch */
  3604. #if 0
  3605. static int gfCheckVal = 1; /* Value checking flag in VpNmlz() */
  3606. #endif
  3607. #endif /* BIGDECIMAL_DEBUG */
  3608. static Real *VpConstOne; /* constant 1.0 */
  3609. static Real *VpPt5; /* constant 0.5 */
  3610. #define maxnr 100UL /* Maximum iterations for calculating sqrt. */
  3611. /* used in VpSqrt() */
  3612. /* ETC */
  3613. #define MemCmp(x,y,z) memcmp(x,y,z)
  3614. #define StrCmp(x,y) strcmp(x,y)
  3615. enum op_sw {
  3616. OP_SW_ADD = 1, /* + */
  3617. OP_SW_SUB, /* - */
  3618. OP_SW_MULT, /* * */
  3619. OP_SW_DIV /* / */
  3620. };
  3621. static int VpIsDefOP(Real *c, Real *a, Real *b, enum op_sw sw);
  3622. static int AddExponent(Real *a, SIGNED_VALUE n);
  3623. static DECDIG VpAddAbs(Real *a,Real *b,Real *c);
  3624. static DECDIG VpSubAbs(Real *a,Real *b,Real *c);
  3625. static size_t VpSetPTR(Real *a, Real *b, Real *c, size_t *a_pos, size_t *b_pos, size_t *c_pos, DECDIG *av, DECDIG *bv);
  3626. static int VpNmlz(Real *a);
  3627. static void VpFormatSt(char *psz, size_t fFmt);
  3628. static int VpRdup(Real *m, size_t ind_m);
  3629. #ifdef BIGDECIMAL_DEBUG
  3630. # ifdef HAVE_RB_EXT_RACTOR_SAFE
  3631. # error Need to make rewiting gnAlloc atomic
  3632. # endif
  3633. static int gnAlloc = 0; /* Memory allocation counter */
  3634. #endif /* BIGDECIMAL_DEBUG */
  3635. VP_EXPORT void *
  3636. VpMemAlloc(size_t mb)
  3637. {
  3638. void *p = xmalloc(mb);
  3639. memset(p, 0, mb);
  3640. #ifdef BIGDECIMAL_DEBUG
  3641. gnAlloc++; /* Count allocation call */
  3642. #endif /* BIGDECIMAL_DEBUG */
  3643. return p;
  3644. }
  3645. VP_EXPORT void *
  3646. VpMemRealloc(void *ptr, size_t mb)
  3647. {
  3648. return xrealloc(ptr, mb);
  3649. }
  3650. VP_EXPORT void
  3651. VpFree(Real *pv)
  3652. {
  3653. if (pv != NULL) {
  3654. xfree(pv);
  3655. #ifdef BIGDECIMAL_DEBUG
  3656. gnAlloc--; /* Decrement allocation count */
  3657. if (gnAlloc == 0) {
  3658. printf(" *************** All memories allocated freed ****************\n");
  3659. /*getchar();*/
  3660. }
  3661. if (gnAlloc < 0) {
  3662. printf(" ??????????? Too many memory free calls(%d) ?????????????\n", gnAlloc);
  3663. /*getchar();*/
  3664. }
  3665. #endif /* BIGDECIMAL_DEBUG */
  3666. }
  3667. }
  3668. /*
  3669. * EXCEPTION Handling.
  3670. */
  3671. #define bigdecimal_set_thread_local_exception_mode(mode) \
  3672. rb_thread_local_aset( \
  3673. rb_thread_current(), \
  3674. id_BigDecimal_exception_mode, \
  3675. INT2FIX((int)(mode)) \
  3676. )
  3677. static unsigned short
  3678. VpGetException (void)
  3679. {
  3680. VALUE const vmode = rb_thread_local_aref(
  3681. rb_thread_current(),
  3682. id_BigDecimal_exception_mode
  3683. );
  3684. if (NIL_P(vmode)) {
  3685. bigdecimal_set_thread_local_exception_mode(BIGDECIMAL_EXCEPTION_MODE_DEFAULT);
  3686. return BIGDECIMAL_EXCEPTION_MODE_DEFAULT;
  3687. }
  3688. return NUM2USHORT(vmode);
  3689. }
  3690. static void
  3691. VpSetException(unsigned short f)
  3692. {
  3693. bigdecimal_set_thread_local_exception_mode(f);
  3694. }
  3695. /*
  3696. * Precision limit.
  3697. */
  3698. #define bigdecimal_set_thread_local_precision_limit(limit) \
  3699. rb_thread_local_aset( \
  3700. rb_thread_current(), \
  3701. id_BigDecimal_precision_limit, \
  3702. SIZET2NUM(limit) \
  3703. )
  3704. #define BIGDECIMAL_PRECISION_LIMIT_DEFAULT ((size_t)0)
  3705. /* These 2 functions added at v1.1.7 */
  3706. VP_EXPORT size_t
  3707. VpGetPrecLimit(void)
  3708. {
  3709. VALUE const vlimit = rb_thread_local_aref(
  3710. rb_thread_current(),
  3711. id_BigDecimal_precision_limit
  3712. );
  3713. if (NIL_P(vlimit)) {
  3714. bigdecimal_set_thread_local_precision_limit(BIGDECIMAL_PRECISION_LIMIT_DEFAULT);
  3715. return BIGDECIMAL_PRECISION_LIMIT_DEFAULT;
  3716. }
  3717. return NUM2SIZET(vlimit);
  3718. }
  3719. VP_EXPORT size_t
  3720. VpSetPrecLimit(size_t n)
  3721. {
  3722. size_t const s = VpGetPrecLimit();
  3723. bigdecimal_set_thread_local_precision_limit(n);
  3724. return s;
  3725. }
  3726. /*
  3727. * Rounding mode.
  3728. */
  3729. #define bigdecimal_set_thread_local_rounding_mode(mode) \
  3730. rb_thread_local_aset( \
  3731. rb_thread_current(), \
  3732. id_BigDecimal_rounding_mode, \
  3733. INT2FIX((int)(mode)) \
  3734. )
  3735. VP_EXPORT unsigned short
  3736. VpGetRoundMode(void)
  3737. {
  3738. VALUE const vmode = rb_thread_local_aref(
  3739. rb_thread_current(),
  3740. id_BigDecimal_rounding_mode
  3741. );
  3742. if (NIL_P(vmode)) {
  3743. bigdecimal_set_thread_local_rounding_mode(BIGDECIMAL_ROUNDING_MODE_DEFAULT);
  3744. return BIGDECIMAL_ROUNDING_MODE_DEFAULT;
  3745. }
  3746. return NUM2USHORT(vmode);
  3747. }
  3748. VP_EXPORT int
  3749. VpIsRoundMode(unsigned short n)
  3750. {
  3751. switch (n) {
  3752. case VP_ROUND_UP:
  3753. case VP_ROUND_DOWN:
  3754. case VP_ROUND_HALF_UP:
  3755. case VP_ROUND_HALF_DOWN:
  3756. case VP_ROUND_CEIL:
  3757. case VP_ROUND_FLOOR:
  3758. case VP_ROUND_HALF_EVEN:
  3759. return 1;
  3760. default:
  3761. return 0;
  3762. }
  3763. }
  3764. VP_EXPORT unsigned short
  3765. VpSetRoundMode(unsigned short n)
  3766. {
  3767. if (VpIsRoundMode(n)) {
  3768. bigdecimal_set_thread_local_rounding_mode(n);
  3769. return n;
  3770. }
  3771. return VpGetRoundMode();
  3772. }
  3773. /*
  3774. * 0.0 & 1.0 generator
  3775. * These gZero_..... and gOne_..... can be any name
  3776. * referenced from nowhere except Zero() and One().
  3777. * gZero_..... and gOne_..... must have global scope
  3778. * (to let the compiler know they may be changed in outside
  3779. * (... but not actually..)).
  3780. */
  3781. volatile const double gOne_ABCED9B4_CE73__00400511F31D = 1.0;
  3782. static double
  3783. One(void)
  3784. {
  3785. return gOne_ABCED9B4_CE73__00400511F31D;
  3786. }
  3787. /*
  3788. ----------------------------------------------------------------
  3789. Value of sign in Real structure is reserved for future use.
  3790. short sign;
  3791. ==0 : NaN
  3792. 1 : Positive zero
  3793. -1 : Negative zero
  3794. 2 : Positive number
  3795. -2 : Negative number
  3796. 3 : Positive infinite number
  3797. -3 : Negative infinite number
  3798. ----------------------------------------------------------------
  3799. */
  3800. VP_EXPORT double
  3801. VpGetDoubleNaN(void) /* Returns the value of NaN */
  3802. {
  3803. return nan("");
  3804. }
  3805. VP_EXPORT double
  3806. VpGetDoublePosInf(void) /* Returns the value of +Infinity */
  3807. {
  3808. return HUGE_VAL;
  3809. }
  3810. VP_EXPORT double
  3811. VpGetDoubleNegInf(void) /* Returns the value of -Infinity */
  3812. {
  3813. return -HUGE_VAL;
  3814. }
  3815. VP_EXPORT double
  3816. VpGetDoubleNegZero(void) /* Returns the value of -0 */
  3817. {
  3818. static double nzero = 1000.0;
  3819. if (nzero != 0.0) nzero = (One()/VpGetDoubleNegInf());
  3820. return nzero;
  3821. }
  3822. #if 0 /* unused */
  3823. VP_EXPORT int
  3824. VpIsNegDoubleZero(double v)
  3825. {
  3826. double z = VpGetDoubleNegZero();
  3827. return MemCmp(&v,&z,sizeof(v))==0;
  3828. }
  3829. #endif
  3830. VP_EXPORT int
  3831. VpException(unsigned short f, const char *str,int always)
  3832. {
  3833. unsigned short const exception_mode = VpGetException();
  3834. if (f == VP_EXCEPTION_OP) always = 1;
  3835. if (always || (exception_mode & f)) {
  3836. switch(f) {
  3837. /* case VP_EXCEPTION_OVERFLOW: */
  3838. case VP_EXCEPTION_ZERODIVIDE:
  3839. case VP_EXCEPTION_INFINITY:
  3840. case VP_EXCEPTION_NaN:
  3841. case VP_EXCEPTION_UNDERFLOW:
  3842. case VP_EXCEPTION_OP:
  3843. rb_raise(rb_eFloatDomainError, "%s", str);
  3844. break;
  3845. default:
  3846. rb_fatal("%s", str);
  3847. }
  3848. }
  3849. return 0; /* 0 Means VpException() raised no exception */
  3850. }
  3851. /* Throw exception or returns 0,when resulting c is Inf or NaN */
  3852. /* sw=1:+ 2:- 3:* 4:/ */
  3853. static int
  3854. VpIsDefOP(Real *c, Real *a, Real *b, enum op_sw sw)
  3855. {
  3856. if (VpIsNaN(a) || VpIsNaN(b)) {
  3857. /* at least a or b is NaN */
  3858. VpSetNaN(c);
  3859. goto NaN;
  3860. }
  3861. if (VpIsInf(a)) {
  3862. if (VpIsInf(b)) {
  3863. switch(sw) {
  3864. case OP_SW_ADD: /* + */
  3865. if (VpGetSign(a) == VpGetSign(b)) {
  3866. VpSetInf(c, VpGetSign(a));
  3867. goto Inf;
  3868. }
  3869. else {
  3870. VpSetNaN(c);
  3871. goto NaN;
  3872. }
  3873. case OP_SW_SUB: /* - */
  3874. if (VpGetSign(a) != VpGetSign(b)) {
  3875. VpSetInf(c, VpGetSign(a));
  3876. goto Inf;
  3877. }
  3878. else {
  3879. VpSetNaN(c);
  3880. goto NaN;
  3881. }
  3882. case OP_SW_MULT: /* * */
  3883. VpSetInf(c, VpGetSign(a)*VpGetSign(b));
  3884. goto Inf;
  3885. case OP_SW_DIV: /* / */
  3886. VpSetNaN(c);
  3887. goto NaN;
  3888. }
  3889. VpSetNaN(c);
  3890. goto NaN;
  3891. }
  3892. /* Inf op Finite */
  3893. switch(sw) {
  3894. case OP_SW_ADD: /* + */
  3895. case OP_SW_SUB: /* - */
  3896. VpSetInf(c, VpGetSign(a));
  3897. break;
  3898. case OP_SW_MULT: /* * */
  3899. if (VpIsZero(b)) {
  3900. VpSetNaN(c);
  3901. goto NaN;
  3902. }
  3903. VpSetInf(c, VpGetSign(a)*VpGetSign(b));
  3904. break;
  3905. case OP_SW_DIV: /* / */
  3906. VpSetInf(c, VpGetSign(a)*VpGetSign(b));
  3907. }
  3908. goto Inf;
  3909. }
  3910. if (VpIsInf(b)) {
  3911. switch(sw) {
  3912. case OP_SW_ADD: /* + */
  3913. VpSetInf(c, VpGetSign(b));
  3914. break;
  3915. case OP_SW_SUB: /* - */
  3916. VpSetInf(c, -VpGetSign(b));
  3917. break;
  3918. case OP_SW_MULT: /* * */
  3919. if (VpIsZero(a)) {
  3920. VpSetNaN(c);
  3921. goto NaN;
  3922. }
  3923. VpSetInf(c, VpGetSign(a)*VpGetSign(b));
  3924. break;
  3925. case OP_SW_DIV: /* / */
  3926. VpSetZero(c, VpGetSign(a)*VpGetSign(b));
  3927. }
  3928. goto Inf;
  3929. }
  3930. return 1; /* Results OK */
  3931. Inf:
  3932. if (VpIsPosInf(c)) {
  3933. return VpException(VP_EXCEPTION_INFINITY, "Computation results to 'Infinity'", 0);
  3934. }
  3935. else {
  3936. return VpException(VP_EXCEPTION_INFINITY, "Computation results to '-Infinity'", 0);
  3937. }
  3938. NaN:
  3939. return VpException(VP_EXCEPTION_NaN, "Computation results to 'NaN'", 0);
  3940. }
  3941. /*
  3942. ----------------------------------------------------------------
  3943. */
  3944. /*
  3945. * returns number of chars needed to represent vp in specified format.
  3946. */
  3947. VP_EXPORT size_t
  3948. VpNumOfChars(Real *vp,const char *pszFmt)
  3949. {
  3950. SIGNED_VALUE ex;
  3951. size_t nc;
  3952. if (vp == NULL) return BASE_FIG*2+6;
  3953. if (!VpIsDef(vp)) return 32; /* not sure,may be OK */
  3954. switch(*pszFmt) {
  3955. case 'F':
  3956. nc = BASE_FIG*(vp->Prec + 1)+2;
  3957. ex = vp->exponent;
  3958. if (ex < 0) {
  3959. nc += BASE_FIG*(size_t)(-ex);
  3960. }
  3961. else {
  3962. if ((size_t)ex > vp->Prec) {
  3963. nc += BASE_FIG*((size_t)ex - vp->Prec);
  3964. }
  3965. }
  3966. break;
  3967. case 'E':
  3968. /* fall through */
  3969. default:
  3970. nc = BASE_FIG*(vp->Prec + 2)+6; /* 3: sign + exponent chars */
  3971. }
  3972. return nc;
  3973. }
  3974. /*
  3975. * Initializer for Vp routines and constants used.
  3976. * [Input]
  3977. * BaseVal: Base value(assigned to BASE) for Vp calculation.
  3978. * It must be the form BaseVal=10**n.(n=1,2,3,...)
  3979. * If Base <= 0L,then the BASE will be calculated so
  3980. * that BASE is as large as possible satisfying the
  3981. * relation MaxVal <= BASE*(BASE+1). Where the value
  3982. * MaxVal is the largest value which can be represented
  3983. * by one DECDIG word in the computer used.
  3984. *
  3985. * [Returns]
  3986. * BIGDECIMAL_DOUBLE_FIGURES ... OK
  3987. */
  3988. VP_EXPORT size_t
  3989. VpInit(DECDIG BaseVal)
  3990. {
  3991. /* Setup +/- Inf NaN -0 */
  3992. VpGetDoubleNegZero();
  3993. /* Allocates Vp constants. */
  3994. VpConstOne = VpAlloc(1UL, "1", 1, 1);
  3995. VpPt5 = VpAlloc(1UL, ".5", 1, 1);
  3996. #ifdef BIGDECIMAL_DEBUG
  3997. gnAlloc = 0;
  3998. #endif /* BIGDECIMAL_DEBUG */
  3999. #ifdef BIGDECIMAL_DEBUG
  4000. if (gfDebug) {
  4001. printf("VpInit: BaseVal = %"PRIuDECDIG"\n", BaseVal);
  4002. printf("\tBASE = %"PRIuDECDIG"\n", BASE);
  4003. printf("\tHALF_BASE = %"PRIuDECDIG"\n", HALF_BASE);
  4004. printf("\tBASE1 = %"PRIuDECDIG"\n", BASE1);
  4005. printf("\tBASE_FIG = %u\n", BASE_FIG);
  4006. printf("\tBIGDECIMAL_DOUBLE_FIGURES = %d\n", BIGDECIMAL_DOUBLE_FIGURES);
  4007. }
  4008. #endif /* BIGDECIMAL_DEBUG */
  4009. return BIGDECIMAL_DOUBLE_FIGURES;
  4010. }
  4011. VP_EXPORT Real *
  4012. VpOne(void)
  4013. {
  4014. return VpConstOne;
  4015. }
  4016. /* If exponent overflows,then raise exception or returns 0 */
  4017. static int
  4018. AddExponent(Real *a, SIGNED_VALUE n)
  4019. {
  4020. SIGNED_VALUE e = a->exponent;
  4021. SIGNED_VALUE m = e+n;
  4022. SIGNED_VALUE eb, mb;
  4023. if (e > 0) {
  4024. if (n > 0) {
  4025. if (MUL_OVERFLOW_SIGNED_VALUE_P(m, (SIGNED_VALUE)BASE_FIG) ||
  4026. MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG))
  4027. goto overflow;
  4028. mb = m*(SIGNED_VALUE)BASE_FIG;
  4029. eb = e*(SIGNED_VALUE)BASE_FIG;
  4030. if (eb - mb > 0) goto overflow;
  4031. }
  4032. }
  4033. else if (n < 0) {
  4034. if (MUL_OVERFLOW_SIGNED_VALUE_P(m, (SIGNED_VALUE)BASE_FIG) ||
  4035. MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG))
  4036. goto underflow;
  4037. mb = m*(SIGNED_VALUE)BASE_FIG;
  4038. eb = e*(SIGNED_VALUE)BASE_FIG;
  4039. if (mb - eb > 0) goto underflow;
  4040. }
  4041. a->exponent = m;
  4042. return 1;
  4043. /* Overflow/Underflow ==> Raise exception or returns 0 */
  4044. underflow:
  4045. VpSetZero(a, VpGetSign(a));
  4046. return VpException(VP_EXCEPTION_UNDERFLOW, "Exponent underflow", 0);
  4047. overflow:
  4048. VpSetInf(a, VpGetSign(a));
  4049. return VpException(VP_EXCEPTION_OVERFLOW, "Exponent overflow", 0);
  4050. }
  4051. Real *
  4052. bigdecimal_parse_special_string(const char *str)
  4053. {
  4054. static const struct {
  4055. const char *str;
  4056. size_t len;
  4057. int sign;
  4058. } table[] = {
  4059. { SZ_INF, sizeof(SZ_INF) - 1, VP_SIGN_POSITIVE_INFINITE },
  4060. { SZ_PINF, sizeof(SZ_PINF) - 1, VP_SIGN_POSITIVE_INFINITE },
  4061. { SZ_NINF, sizeof(SZ_NINF) - 1, VP_SIGN_NEGATIVE_INFINITE },
  4062. { SZ_NaN, sizeof(SZ_NaN) - 1, VP_SIGN_NaN }
  4063. };
  4064. static const size_t table_length = sizeof(table) / sizeof(table[0]);
  4065. size_t i;
  4066. for (i = 0; i < table_length; ++i) {
  4067. const char *p;
  4068. if (strncmp(str, table[i].str, table[i].len) != 0) {
  4069. continue;
  4070. }
  4071. p = str + table[i].len;
  4072. while (*p && ISSPACE(*p)) ++p;
  4073. if (*p == '\0') {
  4074. Real *vp = VpAllocReal(1);
  4075. vp->MaxPrec = 1;
  4076. switch (table[i].sign) {
  4077. default:
  4078. UNREACHABLE; break;
  4079. case VP_SIGN_POSITIVE_INFINITE:
  4080. VpSetPosInf(vp);
  4081. return vp;
  4082. case VP_SIGN_NEGATIVE_INFINITE:
  4083. VpSetNegInf(vp);
  4084. return vp;
  4085. case VP_SIGN_NaN:
  4086. VpSetNaN(vp);
  4087. return vp;
  4088. }
  4089. }
  4090. }
  4091. return NULL;
  4092. }
  4093. /*
  4094. * Allocates variable.
  4095. * [Input]
  4096. * mx ... allocation unit, if zero then mx is determined by szVal.
  4097. * The mx is the number of effective digits can to be stored.
  4098. * szVal ... value assigned(char). If szVal==NULL,then zero is assumed.
  4099. * If szVal[0]=='#' then Max. Prec. will not be considered(1.1.7),
  4100. * full precision specified by szVal is allocated.
  4101. *
  4102. * [Returns]
  4103. * Pointer to the newly allocated variable, or
  4104. * NULL be returned if memory allocation is failed,or any error.
  4105. */
  4106. VP_EXPORT Real *
  4107. VpAlloc(size_t mx, const char *szVal, int strict_p, int exc)
  4108. {
  4109. const char *orig_szVal = szVal;
  4110. size_t i, j, ni, ipf, nf, ipe, ne, dot_seen, exp_seen, nalloc;
  4111. char v, *psz;
  4112. int sign=1;
  4113. Real *vp = NULL;
  4114. size_t mf = VpGetPrecLimit();
  4115. VALUE buf;
  4116. mx = (mx + BASE_FIG - 1) / BASE_FIG; /* Determine allocation unit. */
  4117. if (mx == 0) ++mx;
  4118. if (szVal) {
  4119. /* Skipping leading spaces */
  4120. while (ISSPACE(*szVal)) szVal++;
  4121. /* Processing the leading one `#` */
  4122. if (*szVal != '#') {
  4123. if (mf) {
  4124. mf = (mf + BASE_FIG - 1) / BASE_FIG + 2; /* Needs 1 more for div */
  4125. if (mx > mf) {
  4126. mx = mf;
  4127. }
  4128. }
  4129. }
  4130. else {
  4131. ++szVal;
  4132. }
  4133. }
  4134. else {
  4135. return_zero:
  4136. /* necessary to be able to store */
  4137. /* at least mx digits. */
  4138. /* szVal==NULL ==> allocate zero value. */
  4139. vp = VpAllocReal(mx);
  4140. vp->MaxPrec = mx; /* set max precision */
  4141. VpSetZero(vp, 1); /* initialize vp to zero. */
  4142. return vp;
  4143. }
  4144. /* Check on Inf & NaN */
  4145. if ((vp = bigdecimal_parse_special_string(szVal)) != NULL) {
  4146. return vp;
  4147. }
  4148. /* Scanning digits */
  4149. /* A buffer for keeping scanned digits */
  4150. buf = rb_str_tmp_new(strlen(szVal) + 1);
  4151. psz = RSTRING_PTR(buf);
  4152. /* cursor: i for psz, and j for szVal */
  4153. i = j = 0;
  4154. /* Scanning: sign part */
  4155. v = psz[i] = szVal[j];
  4156. if ((v == '-') || (v == '+')) {
  4157. sign = -(v == '-');
  4158. ++i;
  4159. ++j;
  4160. }
  4161. /* Scanning: integer part */
  4162. ni = 0; /* number of digits in the integer part */
  4163. while ((v = psz[i] = szVal[j]) != '\0') {
  4164. if (!strict_p && ISSPACE(v)) {
  4165. v = psz[i] = '\0';
  4166. break;
  4167. }
  4168. if (v == '_') {
  4169. if (ni > 0) {
  4170. v = szVal[j+1];
  4171. if (v == '\0' || ISSPACE(v) || ISDIGIT(v)) {
  4172. ++j;
  4173. continue;
  4174. }
  4175. if (!strict_p) {
  4176. v = psz[i] = '\0';
  4177. break;
  4178. }
  4179. }
  4180. goto invalid_value;
  4181. }
  4182. if (!ISDIGIT(v)) {
  4183. break;
  4184. }
  4185. ++ni;
  4186. ++i;
  4187. ++j;
  4188. }
  4189. /* Scanning: fractional part */
  4190. nf = 0; /* number of digits in the fractional part */
  4191. ne = 0; /* number of digits in the exponential part */
  4192. ipf = 0; /* index of the beginning of the fractional part */
  4193. ipe = 0; /* index of the beginning of the exponential part */
  4194. dot_seen = 0;
  4195. exp_seen = 0;
  4196. if (v != '\0') {
  4197. /* Scanning fractional part */
  4198. if ((psz[i] = szVal[j]) == '.') {
  4199. dot_seen = 1;
  4200. ++i;
  4201. ++j;
  4202. ipf = i;
  4203. while ((v = psz[i] = szVal[j]) != '\0') {
  4204. if (!strict_p && ISSPACE(v)) {
  4205. v = psz[i] = '\0';
  4206. break;
  4207. }
  4208. if (v == '_') {
  4209. if (nf > 0 && ISDIGIT(szVal[j+1])) {
  4210. ++j;
  4211. continue;
  4212. }
  4213. if (!strict_p) {
  4214. v = psz[i] = '\0';
  4215. if (nf == 0) {
  4216. dot_seen = 0;
  4217. }
  4218. break;
  4219. }
  4220. goto invalid_value;
  4221. }
  4222. if (!ISDIGIT(v)) break;
  4223. ++i;
  4224. ++j;
  4225. ++nf;
  4226. }
  4227. }
  4228. /* Scanning exponential part */
  4229. if (v != '\0') {
  4230. switch ((psz[i] = szVal[j])) {
  4231. case '\0':
  4232. break;
  4233. case 'e': case 'E':
  4234. case 'd': case 'D':
  4235. exp_seen = 1;
  4236. ++i;
  4237. ++j;
  4238. ipe = i;
  4239. v = psz[i] = szVal[j];
  4240. if ((v == '-') || (v == '+')) {
  4241. ++i;
  4242. ++j;
  4243. }
  4244. while ((v = psz[i] = szVal[j]) != '\0') {
  4245. if (!strict_p && ISSPACE(v)) {
  4246. v = psz[i] = '\0';
  4247. break;
  4248. }
  4249. if (v == '_') {
  4250. if (ne > 0 && ISDIGIT(szVal[j+1])) {
  4251. ++j;
  4252. continue;
  4253. }
  4254. if (!strict_p) {
  4255. v = psz[i] = '\0';
  4256. if (ne == 0) {
  4257. exp_seen = 0;
  4258. }
  4259. break;
  4260. }
  4261. goto invalid_value;
  4262. }
  4263. if (!ISDIGIT(v)) break;
  4264. ++i;
  4265. ++j;
  4266. ++ne;
  4267. }
  4268. break;
  4269. default:
  4270. break;
  4271. }
  4272. }
  4273. if (v != '\0') {
  4274. /* Scanning trailing spaces */
  4275. while (ISSPACE(szVal[j])) ++j;
  4276. /* Invalid character */
  4277. if (szVal[j] && strict_p) {
  4278. goto invalid_value;
  4279. }
  4280. }
  4281. }
  4282. psz[i] = '\0';
  4283. if (strict_p && (((ni == 0 || dot_seen) && nf == 0) || (exp_seen && ne == 0))) {
  4284. VALUE str;
  4285. invalid_value:
  4286. if (!strict_p) {
  4287. goto return_zero;
  4288. }
  4289. if (!exc) {
  4290. return NULL;
  4291. }
  4292. str = rb_str_new2(orig_szVal);
  4293. rb_raise(rb_eArgError, "invalid value for BigDecimal(): \"%"PRIsVALUE"\"", str);
  4294. }
  4295. nalloc = (ni + nf + BASE_FIG - 1) / BASE_FIG + 1; /* set effective allocation */
  4296. /* units for szVal[] */
  4297. if (mx == 0) mx = 1;
  4298. nalloc = Max(nalloc, mx);
  4299. mx = nalloc;
  4300. vp = VpAllocReal(mx);
  4301. vp->MaxPrec = mx; /* set max precision */
  4302. VpSetZero(vp, sign);
  4303. VpCtoV(vp, psz, ni, psz + ipf, nf, psz + ipe, ne);
  4304. rb_str_resize(buf, 0);
  4305. return vp;
  4306. }
  4307. /*
  4308. * Assignment(c=a).
  4309. * [Input]
  4310. * a ... RHSV
  4311. * isw ... switch for assignment.
  4312. * c = a when isw > 0
  4313. * c = -a when isw < 0
  4314. * if c->MaxPrec < a->Prec,then round operation
  4315. * will be performed.
  4316. * [Output]
  4317. * c ... LHSV
  4318. */
  4319. VP_EXPORT size_t
  4320. VpAsgn(Real *c, Real *a, int isw)
  4321. {
  4322. size_t n;
  4323. if (VpIsNaN(a)) {
  4324. VpSetNaN(c);
  4325. return 0;
  4326. }
  4327. if (VpIsInf(a)) {
  4328. VpSetInf(c, isw * VpGetSign(a));
  4329. return 0;
  4330. }
  4331. /* check if the RHS is zero */
  4332. if (!VpIsZero(a)) {
  4333. c->exponent = a->exponent; /* store exponent */
  4334. VpSetSign(c, isw * VpGetSign(a)); /* set sign */
  4335. n = (a->Prec < c->MaxPrec) ? (a->Prec) : (c->MaxPrec);
  4336. c->Prec = n;
  4337. memcpy(c->frac, a->frac, n * sizeof(DECDIG));
  4338. /* Needs round ? */
  4339. if (isw != 10) {
  4340. /* Not in ActiveRound */
  4341. if(c->Prec < a->Prec) {
  4342. VpInternalRound(c, n, (n>0) ? a->frac[n-1] : 0, a->frac[n]);
  4343. }
  4344. else {
  4345. VpLimitRound(c,0);
  4346. }
  4347. }
  4348. }
  4349. else {
  4350. /* The value of 'a' is zero. */
  4351. VpSetZero(c, isw * VpGetSign(a));
  4352. return 1;
  4353. }
  4354. return c->Prec * BASE_FIG;
  4355. }
  4356. /*
  4357. * c = a + b when operation = 1 or 2
  4358. * c = a - b when operation = -1 or -2.
  4359. * Returns number of significant digits of c
  4360. */
  4361. VP_EXPORT size_t
  4362. VpAddSub(Real *c, Real *a, Real *b, int operation)
  4363. {
  4364. short sw, isw;
  4365. Real *a_ptr, *b_ptr;
  4366. size_t n, na, nb, i;
  4367. DECDIG mrv;
  4368. #ifdef BIGDECIMAL_DEBUG
  4369. if (gfDebug) {
  4370. VPrint(stdout, "VpAddSub(enter) a=% \n", a);
  4371. VPrint(stdout, " b=% \n", b);
  4372. printf(" operation=%d\n", operation);
  4373. }
  4374. #endif /* BIGDECIMAL_DEBUG */
  4375. if (!VpIsDefOP(c, a, b, (operation > 0) ? OP_SW_ADD : OP_SW_SUB)) return 0; /* No significant digits */
  4376. /* check if a or b is zero */
  4377. if (VpIsZero(a)) {
  4378. /* a is zero,then assign b to c */
  4379. if (!VpIsZero(b)) {
  4380. VpAsgn(c, b, operation);
  4381. }
  4382. else {
  4383. /* Both a and b are zero. */
  4384. if (VpGetSign(a) < 0 && operation * VpGetSign(b) < 0) {
  4385. /* -0 -0 */
  4386. VpSetZero(c, -1);
  4387. }
  4388. else {
  4389. VpSetZero(c, 1);
  4390. }
  4391. return 1; /* 0: 1 significant digits */
  4392. }
  4393. return c->Prec * BASE_FIG;
  4394. }
  4395. if (VpIsZero(b)) {
  4396. /* b is zero,then assign a to c. */
  4397. VpAsgn(c, a, 1);
  4398. return c->Prec*BASE_FIG;
  4399. }
  4400. if (operation < 0) sw = -1;
  4401. else sw = 1;
  4402. /* compare absolute value. As a result,|a_ptr|>=|b_ptr| */
  4403. if (a->exponent > b->exponent) {
  4404. a_ptr = a;
  4405. b_ptr = b;
  4406. } /* |a|>|b| */
  4407. else if (a->exponent < b->exponent) {
  4408. a_ptr = b;
  4409. b_ptr = a;
  4410. } /* |a|<|b| */
  4411. else {
  4412. /* Exponent part of a and b is the same,then compare fraction */
  4413. /* part */
  4414. na = a->Prec;
  4415. nb = b->Prec;
  4416. n = Min(na, nb);
  4417. for (i=0; i < n; ++i) {
  4418. if (a->frac[i] > b->frac[i]) {
  4419. a_ptr = a;
  4420. b_ptr = b;
  4421. goto end_if;
  4422. }
  4423. else if (a->frac[i] < b->frac[i]) {
  4424. a_ptr = b;
  4425. b_ptr = a;
  4426. goto end_if;
  4427. }
  4428. }
  4429. if (na > nb) {
  4430. a_ptr = a;
  4431. b_ptr = b;
  4432. goto end_if;
  4433. }
  4434. else if (na < nb) {
  4435. a_ptr = b;
  4436. b_ptr = a;
  4437. goto end_if;
  4438. }
  4439. /* |a| == |b| */
  4440. if (VpGetSign(a) + sw *VpGetSign(b) == 0) {
  4441. VpSetZero(c, 1); /* abs(a)=abs(b) and operation = '-' */
  4442. return c->Prec * BASE_FIG;
  4443. }
  4444. a_ptr = a;
  4445. b_ptr = b;
  4446. }
  4447. end_if:
  4448. isw = VpGetSign(a) + sw *VpGetSign(b);
  4449. /*
  4450. * isw = 0 ...( 1)+(-1),( 1)-( 1),(-1)+(1),(-1)-(-1)
  4451. * = 2 ...( 1)+( 1),( 1)-(-1)
  4452. * =-2 ...(-1)+(-1),(-1)-( 1)
  4453. * If isw==0, then c =(Sign a_ptr)(|a_ptr|-|b_ptr|)
  4454. * else c =(Sign ofisw)(|a_ptr|+|b_ptr|)
  4455. */
  4456. if (isw) { /* addition */
  4457. VpSetSign(c, 1);
  4458. mrv = VpAddAbs(a_ptr, b_ptr, c);
  4459. VpSetSign(c, isw / 2);
  4460. }
  4461. else { /* subtraction */
  4462. VpSetSign(c, 1);
  4463. mrv = VpSubAbs(a_ptr, b_ptr, c);
  4464. if (a_ptr == a) {
  4465. VpSetSign(c,VpGetSign(a));
  4466. }
  4467. else {
  4468. VpSetSign(c, VpGetSign(a_ptr) * sw);
  4469. }
  4470. }
  4471. VpInternalRound(c, 0, (c->Prec > 0) ? c->frac[c->Prec-1] : 0, mrv);
  4472. #ifdef BIGDECIMAL_DEBUG
  4473. if (gfDebug) {
  4474. VPrint(stdout, "VpAddSub(result) c=% \n", c);
  4475. VPrint(stdout, " a=% \n", a);
  4476. VPrint(stdout, " b=% \n", b);
  4477. printf(" operation=%d\n", operation);
  4478. }
  4479. #endif /* BIGDECIMAL_DEBUG */
  4480. return c->Prec * BASE_FIG;
  4481. }
  4482. /*
  4483. * Addition of two values with variable precision
  4484. * a and b assuming abs(a)>abs(b).
  4485. * c = abs(a) + abs(b) ; where |a|>=|b|
  4486. */
  4487. static DECDIG
  4488. VpAddAbs(Real *a, Real *b, Real *c)
  4489. {
  4490. size_t word_shift;
  4491. size_t ap;
  4492. size_t bp;
  4493. size_t cp;
  4494. size_t a_pos;
  4495. size_t b_pos, b_pos_with_word_shift;
  4496. size_t c_pos;
  4497. DECDIG av, bv, carry, mrv;
  4498. #ifdef BIGDECIMAL_DEBUG
  4499. if (gfDebug) {
  4500. VPrint(stdout, "VpAddAbs called: a = %\n", a);
  4501. VPrint(stdout, " b = %\n", b);
  4502. }
  4503. #endif /* BIGDECIMAL_DEBUG */
  4504. word_shift = VpSetPTR(a, b, c, &ap, &bp, &cp, &av, &bv);
  4505. a_pos = ap;
  4506. b_pos = bp;
  4507. c_pos = cp;
  4508. if (word_shift == (size_t)-1L) return 0; /* Overflow */
  4509. if (b_pos == (size_t)-1L) goto Assign_a;
  4510. mrv = av + bv; /* Most right val. Used for round. */
  4511. /* Just assign the last few digits of b to c because a has no */
  4512. /* corresponding digits to be added. */
  4513. if (b_pos > 0) {
  4514. while (b_pos > 0 && b_pos + word_shift > a_pos) {
  4515. c->frac[--c_pos] = b->frac[--b_pos];
  4516. }
  4517. }
  4518. if (b_pos == 0 && word_shift > a_pos) {
  4519. while (word_shift-- > a_pos) {
  4520. c->frac[--c_pos] = 0;
  4521. }
  4522. }
  4523. /* Just assign the last few digits of a to c because b has no */
  4524. /* corresponding digits to be added. */
  4525. b_pos_with_word_shift = b_pos + word_shift;
  4526. while (a_pos > b_pos_with_word_shift) {
  4527. c->frac[--c_pos] = a->frac[--a_pos];
  4528. }
  4529. carry = 0; /* set first carry be zero */
  4530. /* Now perform addition until every digits of b will be */
  4531. /* exhausted. */
  4532. while (b_pos > 0) {
  4533. c->frac[--c_pos] = a->frac[--a_pos] + b->frac[--b_pos] + carry;
  4534. if (c->frac[c_pos] >= BASE) {
  4535. c->frac[c_pos] -= BASE;
  4536. carry = 1;
  4537. }
  4538. else {
  4539. carry = 0;
  4540. }
  4541. }
  4542. /* Just assign the first few digits of a with considering */
  4543. /* the carry obtained so far because b has been exhausted. */
  4544. while (a_pos > 0) {
  4545. c->frac[--c_pos] = a->frac[--a_pos] + carry;
  4546. if (c->frac[c_pos] >= BASE) {
  4547. c->frac[c_pos] -= BASE;
  4548. carry = 1;
  4549. }
  4550. else {
  4551. carry = 0;
  4552. }
  4553. }
  4554. if (c_pos) c->frac[c_pos - 1] += carry;
  4555. goto Exit;
  4556. Assign_a:
  4557. VpAsgn(c, a, 1);
  4558. mrv = 0;
  4559. Exit:
  4560. #ifdef BIGDECIMAL_DEBUG
  4561. if (gfDebug) {
  4562. VPrint(stdout, "VpAddAbs exit: c=% \n", c);
  4563. }
  4564. #endif /* BIGDECIMAL_DEBUG */
  4565. return mrv;
  4566. }
  4567. /*
  4568. * c = abs(a) - abs(b)
  4569. */
  4570. static DECDIG
  4571. VpSubAbs(Real *a, Real *b, Real *c)
  4572. {
  4573. size_t word_shift;
  4574. size_t ap;
  4575. size_t bp;
  4576. size_t cp;
  4577. size_t a_pos;
  4578. size_t b_pos, b_pos_with_word_shift;
  4579. size_t c_pos;
  4580. DECDIG av, bv, borrow, mrv;
  4581. #ifdef BIGDECIMAL_DEBUG
  4582. if (gfDebug) {
  4583. VPrint(stdout, "VpSubAbs called: a = %\n", a);
  4584. VPrint(stdout, " b = %\n", b);
  4585. }
  4586. #endif /* BIGDECIMAL_DEBUG */
  4587. word_shift = VpSetPTR(a, b, c, &ap, &bp, &cp, &av, &bv);
  4588. a_pos = ap;
  4589. b_pos = bp;
  4590. c_pos = cp;
  4591. if (word_shift == (size_t)-1L) return 0; /* Overflow */
  4592. if (b_pos == (size_t)-1L) goto Assign_a;
  4593. if (av >= bv) {
  4594. mrv = av - bv;
  4595. borrow = 0;
  4596. }
  4597. else {
  4598. mrv = 0;
  4599. borrow = 1;
  4600. }
  4601. /* Just assign the values which are the BASE subtracted by */
  4602. /* each of the last few digits of the b because the a has no */
  4603. /* corresponding digits to be subtracted. */
  4604. if (b_pos + word_shift > a_pos) {
  4605. while (b_pos > 0 && b_pos + word_shift > a_pos) {
  4606. c->frac[--c_pos] = BASE - b->frac[--b_pos] - borrow;
  4607. borrow = 1;
  4608. }
  4609. if (b_pos == 0) {
  4610. while (word_shift > a_pos) {
  4611. --word_shift;
  4612. c->frac[--c_pos] = BASE - borrow;
  4613. borrow = 1;
  4614. }
  4615. }
  4616. }
  4617. /* Just assign the last few digits of a to c because b has no */
  4618. /* corresponding digits to subtract. */
  4619. b_pos_with_word_shift = b_pos + word_shift;
  4620. while (a_pos > b_pos_with_word_shift) {
  4621. c->frac[--c_pos] = a->frac[--a_pos];
  4622. }
  4623. /* Now perform subtraction until every digits of b will be */
  4624. /* exhausted. */
  4625. while (b_pos > 0) {
  4626. --c_pos;
  4627. if (a->frac[--a_pos] < b->frac[--b_pos] + borrow) {
  4628. c->frac[c_pos] = BASE + a->frac[a_pos] - b->frac[b_pos] - borrow;
  4629. borrow = 1;
  4630. }
  4631. else {
  4632. c->frac[c_pos] = a->frac[a_pos] - b->frac[b_pos] - borrow;
  4633. borrow = 0;
  4634. }
  4635. }
  4636. /* Just assign the first few digits of a with considering */
  4637. /* the borrow obtained so far because b has been exhausted. */
  4638. while (a_pos > 0) {
  4639. --c_pos;
  4640. if (a->frac[--a_pos] < borrow) {
  4641. c->frac[c_pos] = BASE + a->frac[a_pos] - borrow;
  4642. borrow = 1;
  4643. }
  4644. else {
  4645. c->frac[c_pos] = a->frac[a_pos] - borrow;
  4646. borrow = 0;
  4647. }
  4648. }
  4649. if (c_pos) c->frac[c_pos - 1] -= borrow;
  4650. goto Exit;
  4651. Assign_a:
  4652. VpAsgn(c, a, 1);
  4653. mrv = 0;
  4654. Exit:
  4655. #ifdef BIGDECIMAL_DEBUG
  4656. if (gfDebug) {
  4657. VPrint(stdout, "VpSubAbs exit: c=% \n", c);
  4658. }
  4659. #endif /* BIGDECIMAL_DEBUG */
  4660. return mrv;
  4661. }
  4662. /*
  4663. * Note: If(av+bv)>= HALF_BASE,then 1 will be added to the least significant
  4664. * digit of c(In case of addition).
  4665. * ------------------------- figure of output -----------------------------------
  4666. * a = xxxxxxxxxxx
  4667. * b = xxxxxxxxxx
  4668. * c =xxxxxxxxxxxxxxx
  4669. * word_shift = | |
  4670. * right_word = | | (Total digits in RHSV)
  4671. * left_word = | | (Total digits in LHSV)
  4672. * a_pos = |
  4673. * b_pos = |
  4674. * c_pos = |
  4675. */
  4676. static size_t
  4677. VpSetPTR(Real *a, Real *b, Real *c, size_t *a_pos, size_t *b_pos, size_t *c_pos, DECDIG *av, DECDIG *bv)
  4678. {
  4679. size_t left_word, right_word, word_shift;
  4680. size_t const round_limit = (VpGetPrecLimit() + BASE_FIG - 1) / BASE_FIG;
  4681. assert(a->exponent >= b->exponent);
  4682. c->frac[0] = 0;
  4683. *av = *bv = 0;
  4684. word_shift = (a->exponent - b->exponent);
  4685. left_word = b->Prec + word_shift;
  4686. right_word = Max(a->Prec, left_word);
  4687. left_word = c->MaxPrec - 1; /* -1 ... prepare for round up */
  4688. /*
  4689. * check if 'round' is needed.
  4690. */
  4691. if (right_word > left_word) { /* round ? */
  4692. /*---------------------------------
  4693. * Actual size of a = xxxxxxAxx
  4694. * Actual size of b = xxxBxxxxx
  4695. * Max. size of c = xxxxxx
  4696. * Round off = |-----|
  4697. * c_pos = |
  4698. * right_word = |
  4699. * a_pos = |
  4700. */
  4701. *c_pos = right_word = left_word + 1; /* Set resulting precision */
  4702. /* be equal to that of c */
  4703. if (a->Prec >= c->MaxPrec) {
  4704. /*
  4705. * a = xxxxxxAxxx
  4706. * c = xxxxxx
  4707. * a_pos = |
  4708. */
  4709. *a_pos = left_word;
  4710. if (*a_pos <= round_limit) {
  4711. *av = a->frac[*a_pos]; /* av is 'A' shown in above. */
  4712. }
  4713. }
  4714. else {
  4715. /*
  4716. * a = xxxxxxx
  4717. * c = xxxxxxxxxx
  4718. * a_pos = |
  4719. */
  4720. *a_pos = a->Prec;
  4721. }
  4722. if (b->Prec + word_shift >= c->MaxPrec) {
  4723. /*
  4724. * a = xxxxxxxxx
  4725. * b = xxxxxxxBxxx
  4726. * c = xxxxxxxxxxx
  4727. * b_pos = |
  4728. */
  4729. if (c->MaxPrec >= word_shift + 1) {
  4730. *b_pos = c->MaxPrec - word_shift - 1;
  4731. if (*b_pos + word_shift <= round_limit) {
  4732. *bv = b->frac[*b_pos];
  4733. }
  4734. }
  4735. else {
  4736. *b_pos = -1L;
  4737. }
  4738. }
  4739. else {
  4740. /*
  4741. * a = xxxxxxxxxxxxxxxx
  4742. * b = xxxxxx
  4743. * c = xxxxxxxxxxxxx
  4744. * b_pos = |
  4745. */
  4746. *b_pos = b->Prec;
  4747. }
  4748. }
  4749. else { /* The MaxPrec of c - 1 > The Prec of a + b */
  4750. /*
  4751. * a = xxxxxxx
  4752. * b = xxxxxx
  4753. * c = xxxxxxxxxxx
  4754. * c_pos = |
  4755. */
  4756. *b_pos = b->Prec;
  4757. *a_pos = a->Prec;
  4758. *c_pos = right_word + 1;
  4759. }
  4760. c->Prec = *c_pos;
  4761. c->exponent = a->exponent;
  4762. if (!AddExponent(c, 1)) return (size_t)-1L;
  4763. return word_shift;
  4764. }
  4765. /*
  4766. * Return number of significant digits
  4767. * c = a * b , Where a = a0a1a2 ... an
  4768. * b = b0b1b2 ... bm
  4769. * c = c0c1c2 ... cl
  4770. * a0 a1 ... an * bm
  4771. * a0 a1 ... an * bm-1
  4772. * . . .
  4773. * . . .
  4774. * a0 a1 .... an * b0
  4775. * +_____________________________
  4776. * c0 c1 c2 ...... cl
  4777. * nc <---|
  4778. * MaxAB |--------------------|
  4779. */
  4780. VP_EXPORT size_t
  4781. VpMult(Real *c, Real *a, Real *b)
  4782. {
  4783. size_t MxIndA, MxIndB, MxIndAB, MxIndC;
  4784. size_t ind_c, i, ii, nc;
  4785. size_t ind_as, ind_ae, ind_bs;
  4786. DECDIG carry;
  4787. DECDIG_DBL s;
  4788. Real *w;
  4789. #ifdef BIGDECIMAL_DEBUG
  4790. if (gfDebug) {
  4791. VPrint(stdout, "VpMult(Enter): a=% \n", a);
  4792. VPrint(stdout, " b=% \n", b);
  4793. }
  4794. #endif /* BIGDECIMAL_DEBUG */
  4795. if (!VpIsDefOP(c, a, b, OP_SW_MULT)) return 0; /* No significant digit */
  4796. if (VpIsZero(a) || VpIsZero(b)) {
  4797. /* at least a or b is zero */
  4798. VpSetZero(c, VpGetSign(a) * VpGetSign(b));
  4799. return 1; /* 0: 1 significant digit */
  4800. }
  4801. if (VpIsOne(a)) {
  4802. VpAsgn(c, b, VpGetSign(a));
  4803. goto Exit;
  4804. }
  4805. if (VpIsOne(b)) {
  4806. VpAsgn(c, a, VpGetSign(b));
  4807. goto Exit;
  4808. }
  4809. if (b->Prec > a->Prec) {
  4810. /* Adjust so that digits(a)>digits(b) */
  4811. w = a;
  4812. a = b;
  4813. b = w;
  4814. }
  4815. w = NULL;
  4816. MxIndA = a->Prec - 1;
  4817. MxIndB = b->Prec - 1;
  4818. MxIndC = c->MaxPrec - 1;
  4819. MxIndAB = a->Prec + b->Prec - 1;
  4820. if (MxIndC < MxIndAB) { /* The Max. prec. of c < Prec(a)+Prec(b) */
  4821. w = c;
  4822. c = VpAlloc((size_t)((MxIndAB + 1) * BASE_FIG), "#0", 1, 1);
  4823. MxIndC = MxIndAB;
  4824. }
  4825. /* set LHSV c info */
  4826. c->exponent = a->exponent; /* set exponent */
  4827. if (!AddExponent(c, b->exponent)) {
  4828. if (w) VpFree(c);
  4829. return 0;
  4830. }
  4831. VpSetSign(c, VpGetSign(a) * VpGetSign(b)); /* set sign */
  4832. carry = 0;
  4833. nc = ind_c = MxIndAB;
  4834. memset(c->frac, 0, (nc + 1) * sizeof(DECDIG)); /* Initialize c */
  4835. c->Prec = nc + 1; /* set precision */
  4836. for (nc = 0; nc < MxIndAB; ++nc, --ind_c) {
  4837. if (nc < MxIndB) { /* The left triangle of the Fig. */
  4838. ind_as = MxIndA - nc;
  4839. ind_ae = MxIndA;
  4840. ind_bs = MxIndB;
  4841. }
  4842. else if (nc <= MxIndA) { /* The middle rectangular of the Fig. */
  4843. ind_as = MxIndA - nc;
  4844. ind_ae = MxIndA - (nc - MxIndB);
  4845. ind_bs = MxIndB;
  4846. }
  4847. else /* if (nc > MxIndA) */ { /* The right triangle of the Fig. */
  4848. ind_as = 0;
  4849. ind_ae = MxIndAB - nc - 1;
  4850. ind_bs = MxIndB - (nc - MxIndA);
  4851. }
  4852. for (i = ind_as; i <= ind_ae; ++i) {
  4853. s = (DECDIG_DBL)a->frac[i] * b->frac[ind_bs--];
  4854. carry = (DECDIG)(s / BASE);
  4855. s -= (DECDIG_DBL)carry * BASE;
  4856. c->frac[ind_c] += (DECDIG)s;
  4857. if (c->frac[ind_c] >= BASE) {
  4858. s = c->frac[ind_c] / BASE;
  4859. carry += (DECDIG)s;
  4860. c->frac[ind_c] -= (DECDIG)(s * BASE);
  4861. }
  4862. if (carry) {
  4863. ii = ind_c;
  4864. while (ii-- > 0) {
  4865. c->frac[ii] += carry;
  4866. if (c->frac[ii] >= BASE) {
  4867. carry = c->frac[ii] / BASE;
  4868. c->frac[ii] -= (carry * BASE);
  4869. }
  4870. else {
  4871. break;
  4872. }
  4873. }
  4874. }
  4875. }
  4876. }
  4877. if (w != NULL) { /* free work variable */
  4878. VpNmlz(c);
  4879. VpAsgn(w, c, 1);
  4880. VpFree(c);
  4881. c = w;
  4882. }
  4883. else {
  4884. VpLimitRound(c,0);
  4885. }
  4886. Exit:
  4887. #ifdef BIGDECIMAL_DEBUG
  4888. if (gfDebug) {
  4889. VPrint(stdout, "VpMult(c=a*b): c=% \n", c);
  4890. VPrint(stdout, " a=% \n", a);
  4891. VPrint(stdout, " b=% \n", b);
  4892. }
  4893. #endif /*BIGDECIMAL_DEBUG */
  4894. return c->Prec*BASE_FIG;
  4895. }
  4896. /*
  4897. * c = a / b, remainder = r
  4898. */
  4899. VP_EXPORT size_t
  4900. VpDivd(Real *c, Real *r, Real *a, Real *b)
  4901. {
  4902. size_t word_a, word_b, word_c, word_r;
  4903. size_t i, n, ind_a, ind_b, ind_c, ind_r;
  4904. size_t nLoop;
  4905. DECDIG_DBL q, b1, b1p1, b1b2, b1b2p1, r1r2;
  4906. DECDIG borrow, borrow1, borrow2;
  4907. DECDIG_DBL qb;
  4908. #ifdef BIGDECIMAL_DEBUG
  4909. if (gfDebug) {
  4910. VPrint(stdout, " VpDivd(c=a/b) a=% \n", a);
  4911. VPrint(stdout, " b=% \n", b);
  4912. }
  4913. #endif /*BIGDECIMAL_DEBUG */
  4914. VpSetNaN(r);
  4915. if (!VpIsDefOP(c, a, b, OP_SW_DIV)) goto Exit;
  4916. if (VpIsZero(a) && VpIsZero(b)) {
  4917. VpSetNaN(c);
  4918. return VpException(VP_EXCEPTION_NaN, "Computation results to 'NaN'", 0);
  4919. }
  4920. if (VpIsZero(b)) {
  4921. VpSetInf(c, VpGetSign(a) * VpGetSign(b));
  4922. return VpException(VP_EXCEPTION_ZERODIVIDE, "Divide by zero", 0);
  4923. }
  4924. if (VpIsZero(a)) {
  4925. /* numerator a is zero */
  4926. VpSetZero(c, VpGetSign(a) * VpGetSign(b));
  4927. VpSetZero(r, VpGetSign(a) * VpGetSign(b));
  4928. goto Exit;
  4929. }
  4930. if (VpIsOne(b)) {
  4931. /* divide by one */
  4932. VpAsgn(c, a, VpGetSign(b));
  4933. VpSetZero(r, VpGetSign(a));
  4934. goto Exit;
  4935. }
  4936. word_a = a->Prec;
  4937. word_b = b->Prec;
  4938. word_c = c->MaxPrec;
  4939. word_r = r->MaxPrec;
  4940. ind_c = 0;
  4941. ind_r = 1;
  4942. if (word_a >= word_r) goto space_error;
  4943. r->frac[0] = 0;
  4944. while (ind_r <= word_a) {
  4945. r->frac[ind_r] = a->frac[ind_r - 1];
  4946. ++ind_r;
  4947. }
  4948. while (ind_r < word_r) r->frac[ind_r++] = 0;
  4949. while (ind_c < word_c) c->frac[ind_c++] = 0;
  4950. /* initial procedure */
  4951. b1 = b1p1 = b->frac[0];
  4952. if (b->Prec <= 1) {
  4953. b1b2p1 = b1b2 = b1p1 * BASE;
  4954. }
  4955. else {
  4956. b1p1 = b1 + 1;
  4957. b1b2p1 = b1b2 = b1 * BASE + b->frac[1];
  4958. if (b->Prec > 2) ++b1b2p1;
  4959. }
  4960. /* */
  4961. /* loop start */
  4962. ind_c = word_r - 1;
  4963. nLoop = Min(word_c,ind_c);
  4964. ind_c = 1;
  4965. while (ind_c < nLoop) {
  4966. if (r->frac[ind_c] == 0) {
  4967. ++ind_c;
  4968. continue;
  4969. }
  4970. r1r2 = (DECDIG_DBL)r->frac[ind_c] * BASE + r->frac[ind_c + 1];
  4971. if (r1r2 == b1b2) {
  4972. /* The first two word digits is the same */
  4973. ind_b = 2;
  4974. ind_a = ind_c + 2;
  4975. while (ind_b < word_b) {
  4976. if (r->frac[ind_a] < b->frac[ind_b]) goto div_b1p1;
  4977. if (r->frac[ind_a] > b->frac[ind_b]) break;
  4978. ++ind_a;
  4979. ++ind_b;
  4980. }
  4981. /* The first few word digits of r and b is the same and */
  4982. /* the first different word digit of w is greater than that */
  4983. /* of b, so quotient is 1 and just subtract b from r. */
  4984. borrow = 0; /* quotient=1, then just r-b */
  4985. ind_b = b->Prec - 1;
  4986. ind_r = ind_c + ind_b;
  4987. if (ind_r >= word_r) goto space_error;
  4988. n = ind_b;
  4989. for (i = 0; i <= n; ++i) {
  4990. if (r->frac[ind_r] < b->frac[ind_b] + borrow) {
  4991. r->frac[ind_r] += (BASE - (b->frac[ind_b] + borrow));
  4992. borrow = 1;
  4993. }
  4994. else {
  4995. r->frac[ind_r] = r->frac[ind_r] - b->frac[ind_b] - borrow;
  4996. borrow = 0;
  4997. }
  4998. --ind_r;
  4999. --ind_b;
  5000. }
  5001. ++c->frac[ind_c];
  5002. goto carry;
  5003. }
  5004. /* The first two word digits is not the same, */
  5005. /* then compare magnitude, and divide actually. */
  5006. if (r1r2 >= b1b2p1) {
  5007. q = r1r2 / b1b2p1; /* q == (DECDIG)q */
  5008. c->frac[ind_c] += (DECDIG)q;
  5009. ind_r = b->Prec + ind_c - 1;
  5010. goto sub_mult;
  5011. }
  5012. div_b1p1:
  5013. if (ind_c + 1 >= word_c) goto out_side;
  5014. q = r1r2 / b1p1; /* q == (DECDIG)q */
  5015. c->frac[ind_c + 1] += (DECDIG)q;
  5016. ind_r = b->Prec + ind_c;
  5017. sub_mult:
  5018. borrow1 = borrow2 = 0;
  5019. ind_b = word_b - 1;
  5020. if (ind_r >= word_r) goto space_error;
  5021. n = ind_b;
  5022. for (i = 0; i <= n; ++i) {
  5023. /* now, perform r = r - q * b */
  5024. qb = q * b->frac[ind_b];
  5025. if (qb < BASE) borrow1 = 0;
  5026. else {
  5027. borrow1 = (DECDIG)(qb / BASE);
  5028. qb -= (DECDIG_DBL)borrow1 * BASE; /* get qb < BASE */
  5029. }
  5030. if(r->frac[ind_r] < qb) {
  5031. r->frac[ind_r] += (DECDIG)(BASE - qb);
  5032. borrow2 = borrow2 + borrow1 + 1;
  5033. }
  5034. else {
  5035. r->frac[ind_r] -= (DECDIG)qb;
  5036. borrow2 += borrow1;
  5037. }
  5038. if (borrow2) {
  5039. if(r->frac[ind_r - 1] < borrow2) {
  5040. r->frac[ind_r - 1] += (BASE - borrow2);
  5041. borrow2 = 1;
  5042. }
  5043. else {
  5044. r->frac[ind_r - 1] -= borrow2;
  5045. borrow2 = 0;
  5046. }
  5047. }
  5048. --ind_r;
  5049. --ind_b;
  5050. }
  5051. r->frac[ind_r] -= borrow2;
  5052. carry:
  5053. ind_r = ind_c;
  5054. while (c->frac[ind_r] >= BASE) {
  5055. c->frac[ind_r] -= BASE;
  5056. --ind_r;
  5057. ++c->frac[ind_r];
  5058. }
  5059. }
  5060. /* End of operation, now final arrangement */
  5061. out_side:
  5062. c->Prec = word_c;
  5063. c->exponent = a->exponent;
  5064. if (!AddExponent(c, 2)) return 0;
  5065. if (!AddExponent(c, -(b->exponent))) return 0;
  5066. VpSetSign(c, VpGetSign(a) * VpGetSign(b));
  5067. VpNmlz(c); /* normalize c */
  5068. r->Prec = word_r;
  5069. r->exponent = a->exponent;
  5070. if (!AddExponent(r, 1)) return 0;
  5071. VpSetSign(r, VpGetSign(a));
  5072. VpNmlz(r); /* normalize r(remainder) */
  5073. goto Exit;
  5074. space_error:
  5075. #ifdef BIGDECIMAL_DEBUG
  5076. if (gfDebug) {
  5077. printf(" word_a=%"PRIuSIZE"\n", word_a);
  5078. printf(" word_b=%"PRIuSIZE"\n", word_b);
  5079. printf(" word_c=%"PRIuSIZE"\n", word_c);
  5080. printf(" word_r=%"PRIuSIZE"\n", word_r);
  5081. printf(" ind_r =%"PRIuSIZE"\n", ind_r);
  5082. }
  5083. #endif /* BIGDECIMAL_DEBUG */
  5084. rb_bug("ERROR(VpDivd): space for remainder too small.");
  5085. Exit:
  5086. #ifdef BIGDECIMAL_DEBUG
  5087. if (gfDebug) {
  5088. VPrint(stdout, " VpDivd(c=a/b), c=% \n", c);
  5089. VPrint(stdout, " r=% \n", r);
  5090. }
  5091. #endif /* BIGDECIMAL_DEBUG */
  5092. return c->Prec * BASE_FIG;
  5093. }
  5094. /*
  5095. * Input a = 00000xxxxxxxx En(5 preceding zeros)
  5096. * Output a = xxxxxxxx En-5
  5097. */
  5098. static int
  5099. VpNmlz(Real *a)
  5100. {
  5101. size_t ind_a, i;
  5102. if (!VpIsDef(a)) goto NoVal;
  5103. if (VpIsZero(a)) goto NoVal;
  5104. ind_a = a->Prec;
  5105. while (ind_a--) {
  5106. if (a->frac[ind_a]) {
  5107. a->Prec = ind_a + 1;
  5108. i = 0;
  5109. while (a->frac[i] == 0) ++i; /* skip the first few zeros */
  5110. if (i) {
  5111. a->Prec -= i;
  5112. if (!AddExponent(a, -(SIGNED_VALUE)i)) return 0;
  5113. memmove(&a->frac[0], &a->frac[i], a->Prec*sizeof(DECDIG));
  5114. }
  5115. return 1;
  5116. }
  5117. }
  5118. /* a is zero(no non-zero digit) */
  5119. VpSetZero(a, VpGetSign(a));
  5120. return 0;
  5121. NoVal:
  5122. a->frac[0] = 0;
  5123. a->Prec = 1;
  5124. return 0;
  5125. }
  5126. /*
  5127. * VpComp = 0 ... if a=b,
  5128. * Pos ... a>b,
  5129. * Neg ... a<b.
  5130. * 999 ... result undefined(NaN)
  5131. */
  5132. VP_EXPORT int
  5133. VpComp(Real *a, Real *b)
  5134. {
  5135. int val;
  5136. size_t mx, ind;
  5137. int e;
  5138. val = 0;
  5139. if (VpIsNaN(a) || VpIsNaN(b)) return 999;
  5140. if (!VpIsDef(a)) {
  5141. if (!VpIsDef(b)) e = a->sign - b->sign;
  5142. else e = a->sign;
  5143. if (e > 0) return 1;
  5144. else if (e < 0) return -1;
  5145. else return 0;
  5146. }
  5147. if (!VpIsDef(b)) {
  5148. e = -b->sign;
  5149. if (e > 0) return 1;
  5150. else return -1;
  5151. }
  5152. /* Zero check */
  5153. if (VpIsZero(a)) {
  5154. if (VpIsZero(b)) return 0; /* both zero */
  5155. val = -VpGetSign(b);
  5156. goto Exit;
  5157. }
  5158. if (VpIsZero(b)) {
  5159. val = VpGetSign(a);
  5160. goto Exit;
  5161. }
  5162. /* compare sign */
  5163. if (VpGetSign(a) > VpGetSign(b)) {
  5164. val = 1; /* a>b */
  5165. goto Exit;
  5166. }
  5167. if (VpGetSign(a) < VpGetSign(b)) {
  5168. val = -1; /* a<b */
  5169. goto Exit;
  5170. }
  5171. /* a and b have same sign, && sign!=0,then compare exponent */
  5172. if (a->exponent > b->exponent) {
  5173. val = VpGetSign(a);
  5174. goto Exit;
  5175. }
  5176. if (a->exponent < b->exponent) {
  5177. val = -VpGetSign(b);
  5178. goto Exit;
  5179. }
  5180. /* a and b have same exponent, then compare their significand. */
  5181. mx = (a->Prec < b->Prec) ? a->Prec : b->Prec;
  5182. ind = 0;
  5183. while (ind < mx) {
  5184. if (a->frac[ind] > b->frac[ind]) {
  5185. val = VpGetSign(a);
  5186. goto Exit;
  5187. }
  5188. if (a->frac[ind] < b->frac[ind]) {
  5189. val = -VpGetSign(b);
  5190. goto Exit;
  5191. }
  5192. ++ind;
  5193. }
  5194. if (a->Prec > b->Prec) {
  5195. val = VpGetSign(a);
  5196. }
  5197. else if (a->Prec < b->Prec) {
  5198. val = -VpGetSign(b);
  5199. }
  5200. Exit:
  5201. if (val > 1) val = 1;
  5202. else if (val < -1) val = -1;
  5203. #ifdef BIGDECIMAL_DEBUG
  5204. if (gfDebug) {
  5205. VPrint(stdout, " VpComp a=%\n", a);
  5206. VPrint(stdout, " b=%\n", b);
  5207. printf(" ans=%d\n", val);
  5208. }
  5209. #endif /* BIGDECIMAL_DEBUG */
  5210. return (int)val;
  5211. }
  5212. /*
  5213. * cntl_chr ... ASCIIZ Character, print control characters
  5214. * Available control codes:
  5215. * % ... VP variable. To print '%', use '%%'.
  5216. * \n ... new line
  5217. * \b ... backspace
  5218. * \t ... tab
  5219. * Note: % must not appear more than once
  5220. * a ... VP variable to be printed
  5221. */
  5222. #ifdef BIGDECIMAL_ENABLE_VPRINT
  5223. static int
  5224. VPrint(FILE *fp, const char *cntl_chr, Real *a)
  5225. {
  5226. size_t i, j, nc, nd, ZeroSup, sep = 10;
  5227. DECDIG m, e, nn;
  5228. j = 0;
  5229. nd = nc = 0; /* nd : number of digits in fraction part(every 10 digits, */
  5230. /* nd<=10). */
  5231. /* nc : number of characters printed */
  5232. ZeroSup = 1; /* Flag not to print the leading zeros as 0.00xxxxEnn */
  5233. while (*(cntl_chr + j)) {
  5234. if (*(cntl_chr + j) == '%' && *(cntl_chr + j + 1) != '%') {
  5235. nc = 0;
  5236. if (VpIsNaN(a)) {
  5237. fprintf(fp, SZ_NaN);
  5238. nc += 8;
  5239. }
  5240. else if (VpIsPosInf(a)) {
  5241. fprintf(fp, SZ_INF);
  5242. nc += 8;
  5243. }
  5244. else if (VpIsNegInf(a)) {
  5245. fprintf(fp, SZ_NINF);
  5246. nc += 9;
  5247. }
  5248. else if (!VpIsZero(a)) {
  5249. if (BIGDECIMAL_NEGATIVE_P(a)) {
  5250. fprintf(fp, "-");
  5251. ++nc;
  5252. }
  5253. nc += fprintf(fp, "0.");
  5254. switch (*(cntl_chr + j + 1)) {
  5255. default:
  5256. break;
  5257. case '0': case 'z':
  5258. ZeroSup = 0;
  5259. ++j;
  5260. sep = cntl_chr[j] == 'z' ? BIGDECIMAL_COMPONENT_FIGURES : 10;
  5261. break;
  5262. }
  5263. for (i = 0; i < a->Prec; ++i) {
  5264. m = BASE1;
  5265. e = a->frac[i];
  5266. while (m) {
  5267. nn = e / m;
  5268. if (!ZeroSup || nn) {
  5269. nc += fprintf(fp, "%lu", (unsigned long)nn); /* The leading zero(s) */
  5270. /* as 0.00xx will not */
  5271. /* be printed. */
  5272. ++nd;
  5273. ZeroSup = 0; /* Set to print succeeding zeros */
  5274. }
  5275. if (nd >= sep) { /* print ' ' after every 10 digits */
  5276. nd = 0;
  5277. nc += fprintf(fp, " ");
  5278. }
  5279. e = e - nn * m;
  5280. m /= 10;
  5281. }
  5282. }
  5283. nc += fprintf(fp, "E%"PRIdSIZE, VpExponent10(a));
  5284. nc += fprintf(fp, " (%"PRIdVALUE", %lu, %lu)", a->exponent, a->Prec, a->MaxPrec);
  5285. }
  5286. else {
  5287. nc += fprintf(fp, "0.0");
  5288. }
  5289. }
  5290. else {
  5291. ++nc;
  5292. if (*(cntl_chr + j) == '\\') {
  5293. switch (*(cntl_chr + j + 1)) {
  5294. case 'n':
  5295. fprintf(fp, "\n");
  5296. ++j;
  5297. break;
  5298. case 't':
  5299. fprintf(fp, "\t");
  5300. ++j;
  5301. break;
  5302. case 'b':
  5303. fprintf(fp, "\n");
  5304. ++j;
  5305. break;
  5306. default:
  5307. fprintf(fp, "%c", *(cntl_chr + j));
  5308. break;
  5309. }
  5310. }
  5311. else {
  5312. fprintf(fp, "%c", *(cntl_chr + j));
  5313. if (*(cntl_chr + j) == '%') ++j;
  5314. }
  5315. }
  5316. j++;
  5317. }
  5318. return (int)nc;
  5319. }
  5320. #endif
  5321. static void
  5322. VpFormatSt(char *psz, size_t fFmt)
  5323. {
  5324. size_t ie, i, nf = 0;
  5325. char ch;
  5326. if (fFmt == 0) return;
  5327. ie = strlen(psz);
  5328. for (i = 0; i < ie; ++i) {
  5329. ch = psz[i];
  5330. if (!ch) break;
  5331. if (ISSPACE(ch) || ch=='-' || ch=='+') continue;
  5332. if (ch == '.') { nf = 0; continue; }
  5333. if (ch == 'E' || ch == 'e') break;
  5334. if (++nf > fFmt) {
  5335. memmove(psz + i + 1, psz + i, ie - i + 1);
  5336. ++ie;
  5337. nf = 0;
  5338. psz[i] = ' ';
  5339. }
  5340. }
  5341. }
  5342. VP_EXPORT ssize_t
  5343. VpExponent10(Real *a)
  5344. {
  5345. ssize_t ex;
  5346. size_t n;
  5347. if (!VpHasVal(a)) return 0;
  5348. ex = a->exponent * (ssize_t)BASE_FIG;
  5349. n = BASE1;
  5350. while ((a->frac[0] / n) == 0) {
  5351. --ex;
  5352. n /= 10;
  5353. }
  5354. return ex;
  5355. }
  5356. VP_EXPORT void
  5357. VpSzMantissa(Real *a,char *psz)
  5358. {
  5359. size_t i, n, ZeroSup;
  5360. DECDIG_DBL m, e, nn;
  5361. if (VpIsNaN(a)) {
  5362. sprintf(psz, SZ_NaN);
  5363. return;
  5364. }
  5365. if (VpIsPosInf(a)) {
  5366. sprintf(psz, SZ_INF);
  5367. return;
  5368. }
  5369. if (VpIsNegInf(a)) {
  5370. sprintf(psz, SZ_NINF);
  5371. return;
  5372. }
  5373. ZeroSup = 1; /* Flag not to print the leading zeros as 0.00xxxxEnn */
  5374. if (!VpIsZero(a)) {
  5375. if (BIGDECIMAL_NEGATIVE_P(a)) *psz++ = '-';
  5376. n = a->Prec;
  5377. for (i = 0; i < n; ++i) {
  5378. m = BASE1;
  5379. e = a->frac[i];
  5380. while (m) {
  5381. nn = e / m;
  5382. if (!ZeroSup || nn) {
  5383. sprintf(psz, "%lu", (unsigned long)nn); /* The leading zero(s) */
  5384. psz += strlen(psz);
  5385. /* as 0.00xx will be ignored. */
  5386. ZeroSup = 0; /* Set to print succeeding zeros */
  5387. }
  5388. e = e - nn * m;
  5389. m /= 10;
  5390. }
  5391. }
  5392. *psz = 0;
  5393. while (psz[-1] == '0') *(--psz) = 0;
  5394. }
  5395. else {
  5396. if (VpIsPosZero(a)) sprintf(psz, "0");
  5397. else sprintf(psz, "-0");
  5398. }
  5399. }
  5400. VP_EXPORT int
  5401. VpToSpecialString(Real *a,char *psz,int fPlus)
  5402. /* fPlus = 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
  5403. {
  5404. if (VpIsNaN(a)) {
  5405. sprintf(psz,SZ_NaN);
  5406. return 1;
  5407. }
  5408. if (VpIsPosInf(a)) {
  5409. if (fPlus == 1) {
  5410. *psz++ = ' ';
  5411. }
  5412. else if (fPlus == 2) {
  5413. *psz++ = '+';
  5414. }
  5415. sprintf(psz, SZ_INF);
  5416. return 1;
  5417. }
  5418. if (VpIsNegInf(a)) {
  5419. sprintf(psz, SZ_NINF);
  5420. return 1;
  5421. }
  5422. if (VpIsZero(a)) {
  5423. if (VpIsPosZero(a)) {
  5424. if (fPlus == 1) sprintf(psz, " 0.0");
  5425. else if (fPlus == 2) sprintf(psz, "+0.0");
  5426. else sprintf(psz, "0.0");
  5427. }
  5428. else sprintf(psz, "-0.0");
  5429. return 1;
  5430. }
  5431. return 0;
  5432. }
  5433. VP_EXPORT void
  5434. VpToString(Real *a, char *psz, size_t fFmt, int fPlus)
  5435. /* fPlus = 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
  5436. {
  5437. size_t i, n, ZeroSup;
  5438. DECDIG shift, m, e, nn;
  5439. char *pszSav = psz;
  5440. ssize_t ex;
  5441. if (VpToSpecialString(a, psz, fPlus)) return;
  5442. ZeroSup = 1; /* Flag not to print the leading zeros as 0.00xxxxEnn */
  5443. if (BIGDECIMAL_NEGATIVE_P(a)) *psz++ = '-';
  5444. else if (fPlus == 1) *psz++ = ' ';
  5445. else if (fPlus == 2) *psz++ = '+';
  5446. *psz++ = '0';
  5447. *psz++ = '.';
  5448. n = a->Prec;
  5449. for (i = 0; i < n; ++i) {
  5450. m = BASE1;
  5451. e = a->frac[i];
  5452. while (m) {
  5453. nn = e / m;
  5454. if (!ZeroSup || nn) {
  5455. sprintf(psz, "%lu", (unsigned long)nn); /* The reading zero(s) */
  5456. psz += strlen(psz);
  5457. /* as 0.00xx will be ignored. */
  5458. ZeroSup = 0; /* Set to print succeeding zeros */
  5459. }
  5460. e = e - nn * m;
  5461. m /= 10;
  5462. }
  5463. }
  5464. ex = a->exponent * (ssize_t)BASE_FIG;
  5465. shift = BASE1;
  5466. while (a->frac[0] / shift == 0) {
  5467. --ex;
  5468. shift /= 10;
  5469. }
  5470. while (psz[-1] == '0') {
  5471. *(--psz) = 0;
  5472. }
  5473. sprintf(psz, "e%"PRIdSIZE, ex);
  5474. if (fFmt) VpFormatSt(pszSav, fFmt);
  5475. }
  5476. VP_EXPORT void
  5477. VpToFString(Real *a, char *psz, size_t fFmt, int fPlus)
  5478. /* fPlus = 0: default, 1: set ' ' before digits, 2: set '+' before digits. */
  5479. {
  5480. size_t i, n;
  5481. DECDIG m, e, nn;
  5482. char *pszSav = psz;
  5483. ssize_t ex;
  5484. if (VpToSpecialString(a, psz, fPlus)) return;
  5485. if (BIGDECIMAL_NEGATIVE_P(a)) *psz++ = '-';
  5486. else if (fPlus == 1) *psz++ = ' ';
  5487. else if (fPlus == 2) *psz++ = '+';
  5488. n = a->Prec;
  5489. ex = a->exponent;
  5490. if (ex <= 0) {
  5491. *psz++ = '0';*psz++ = '.';
  5492. while (ex < 0) {
  5493. for (i=0; i < BASE_FIG; ++i) *psz++ = '0';
  5494. ++ex;
  5495. }
  5496. ex = -1;
  5497. }
  5498. for (i = 0; i < n; ++i) {
  5499. --ex;
  5500. if (i == 0 && ex >= 0) {
  5501. sprintf(psz, "%lu", (unsigned long)a->frac[i]);
  5502. psz += strlen(psz);
  5503. }
  5504. else {
  5505. m = BASE1;
  5506. e = a->frac[i];
  5507. while (m) {
  5508. nn = e / m;
  5509. *psz++ = (char)(nn + '0');
  5510. e = e - nn * m;
  5511. m /= 10;
  5512. }
  5513. }
  5514. if (ex == 0) *psz++ = '.';
  5515. }
  5516. while (--ex>=0) {
  5517. m = BASE;
  5518. while (m /= 10) *psz++ = '0';
  5519. if (ex == 0) *psz++ = '.';
  5520. }
  5521. *psz = 0;
  5522. while (psz[-1] == '0') *(--psz) = 0;
  5523. if (psz[-1] == '.') sprintf(psz, "0");
  5524. if (fFmt) VpFormatSt(pszSav, fFmt);
  5525. }
  5526. /*
  5527. * [Output]
  5528. * a[] ... variable to be assigned the value.
  5529. * [Input]
  5530. * int_chr[] ... integer part(may include '+/-').
  5531. * ni ... number of characters in int_chr[],not including '+/-'.
  5532. * frac[] ... fraction part.
  5533. * nf ... number of characters in frac[].
  5534. * exp_chr[] ... exponent part(including '+/-').
  5535. * ne ... number of characters in exp_chr[],not including '+/-'.
  5536. */
  5537. VP_EXPORT int
  5538. VpCtoV(Real *a, const char *int_chr, size_t ni, const char *frac, size_t nf, const char *exp_chr, size_t ne)
  5539. {
  5540. size_t i, j, ind_a, ma, mi, me;
  5541. SIGNED_VALUE e, es, eb, ef;
  5542. int sign, signe, exponent_overflow;
  5543. /* get exponent part */
  5544. e = 0;
  5545. ma = a->MaxPrec;
  5546. mi = ni;
  5547. me = ne;
  5548. signe = 1;
  5549. exponent_overflow = 0;
  5550. memset(a->frac, 0, ma * sizeof(DECDIG));
  5551. if (ne > 0) {
  5552. i = 0;
  5553. if (exp_chr[0] == '-') {
  5554. signe = -1;
  5555. ++i;
  5556. ++me;
  5557. }
  5558. else if (exp_chr[0] == '+') {
  5559. ++i;
  5560. ++me;
  5561. }
  5562. while (i < me) {
  5563. if (MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG)) {
  5564. es = e;
  5565. goto exp_overflow;
  5566. }
  5567. es = e * (SIGNED_VALUE)BASE_FIG;
  5568. if (MUL_OVERFLOW_SIGNED_VALUE_P(e, 10) ||
  5569. SIGNED_VALUE_MAX - (exp_chr[i] - '0') < e * 10)
  5570. goto exp_overflow;
  5571. e = e * 10 + exp_chr[i] - '0';
  5572. if (MUL_OVERFLOW_SIGNED_VALUE_P(e, (SIGNED_VALUE)BASE_FIG))
  5573. goto exp_overflow;
  5574. if (es > (SIGNED_VALUE)(e * BASE_FIG)) {
  5575. exp_overflow:
  5576. exponent_overflow = 1;
  5577. e = es; /* keep sign */
  5578. break;
  5579. }
  5580. ++i;
  5581. }
  5582. }
  5583. /* get integer part */
  5584. i = 0;
  5585. sign = 1;
  5586. if (1 /*ni >= 0*/) {
  5587. if (int_chr[0] == '-') {
  5588. sign = -1;
  5589. ++i;
  5590. ++mi;
  5591. }
  5592. else if (int_chr[0] == '+') {
  5593. ++i;
  5594. ++mi;
  5595. }
  5596. }
  5597. e = signe * e; /* e: The value of exponent part. */
  5598. e = e + ni; /* set actual exponent size. */
  5599. if (e > 0) signe = 1;
  5600. else signe = -1;
  5601. /* Adjust the exponent so that it is the multiple of BASE_FIG. */
  5602. j = 0;
  5603. ef = 1;
  5604. while (ef) {
  5605. if (e >= 0) eb = e;
  5606. else eb = -e;
  5607. ef = eb / (SIGNED_VALUE)BASE_FIG;
  5608. ef = eb - ef * (SIGNED_VALUE)BASE_FIG;
  5609. if (ef) {
  5610. ++j; /* Means to add one more preceding zero */
  5611. ++e;
  5612. }
  5613. }
  5614. eb = e / (SIGNED_VALUE)BASE_FIG;
  5615. if (exponent_overflow) {
  5616. int zero = 1;
  5617. for ( ; i < mi && zero; i++) zero = int_chr[i] == '0';
  5618. for (i = 0; i < nf && zero; i++) zero = frac[i] == '0';
  5619. if (!zero && signe > 0) {
  5620. VpSetInf(a, sign);
  5621. VpException(VP_EXCEPTION_INFINITY, "exponent overflow",0);
  5622. }
  5623. else VpSetZero(a, sign);
  5624. return 1;
  5625. }
  5626. ind_a = 0;
  5627. while (i < mi) {
  5628. a->frac[ind_a] = 0;
  5629. while (j < BASE_FIG && i < mi) {
  5630. a->frac[ind_a] = a->frac[ind_a] * 10 + int_chr[i] - '0';
  5631. ++j;
  5632. ++i;
  5633. }
  5634. if (i < mi) {
  5635. ++ind_a;
  5636. if (ind_a >= ma) goto over_flow;
  5637. j = 0;
  5638. }
  5639. }
  5640. /* get fraction part */
  5641. i = 0;
  5642. while (i < nf) {
  5643. while (j < BASE_FIG && i < nf) {
  5644. a->frac[ind_a] = a->frac[ind_a] * 10 + frac[i] - '0';
  5645. ++j;
  5646. ++i;
  5647. }
  5648. if (i < nf) {
  5649. ++ind_a;
  5650. if (ind_a >= ma) goto over_flow;
  5651. j = 0;
  5652. }
  5653. }
  5654. goto Final;
  5655. over_flow:
  5656. rb_warn("Conversion from String to BigDecimal overflow (last few digits discarded).");
  5657. Final:
  5658. if (ind_a >= ma) ind_a = ma - 1;
  5659. while (j < BASE_FIG) {
  5660. a->frac[ind_a] = a->frac[ind_a] * 10;
  5661. ++j;
  5662. }
  5663. a->Prec = ind_a + 1;
  5664. a->exponent = eb;
  5665. VpSetSign(a, sign);
  5666. VpNmlz(a);
  5667. return 1;
  5668. }
  5669. /*
  5670. * [Input]
  5671. * *m ... Real
  5672. * [Output]
  5673. * *d ... fraction part of m(d = 0.xxxxxxx). where # of 'x's is fig.
  5674. * *e ... exponent of m.
  5675. * BIGDECIMAL_DOUBLE_FIGURES ... Number of digits in a double variable.
  5676. *
  5677. * m -> d*10**e, 0<d<BASE
  5678. * [Returns]
  5679. * 0 ... Zero
  5680. * 1 ... Normal
  5681. * 2 ... Infinity
  5682. * -1 ... NaN
  5683. */
  5684. VP_EXPORT int
  5685. VpVtoD(double *d, SIGNED_VALUE *e, Real *m)
  5686. {
  5687. size_t ind_m, mm, fig;
  5688. double div;
  5689. int f = 1;
  5690. if (VpIsNaN(m)) {
  5691. *d = VpGetDoubleNaN();
  5692. *e = 0;
  5693. f = -1; /* NaN */
  5694. goto Exit;
  5695. }
  5696. else if (VpIsPosZero(m)) {
  5697. *d = 0.0;
  5698. *e = 0;
  5699. f = 0;
  5700. goto Exit;
  5701. }
  5702. else if (VpIsNegZero(m)) {
  5703. *d = VpGetDoubleNegZero();
  5704. *e = 0;
  5705. f = 0;
  5706. goto Exit;
  5707. }
  5708. else if (VpIsPosInf(m)) {
  5709. *d = VpGetDoublePosInf();
  5710. *e = 0;
  5711. f = 2;
  5712. goto Exit;
  5713. }
  5714. else if (VpIsNegInf(m)) {
  5715. *d = VpGetDoubleNegInf();
  5716. *e = 0;
  5717. f = 2;
  5718. goto Exit;
  5719. }
  5720. /* Normal number */
  5721. fig = roomof(BIGDECIMAL_DOUBLE_FIGURES, BASE_FIG);
  5722. ind_m = 0;
  5723. mm = Min(fig, m->Prec);
  5724. *d = 0.0;
  5725. div = 1.;
  5726. while (ind_m < mm) {
  5727. div /= (double)BASE;
  5728. *d = *d + (double)m->frac[ind_m++] * div;
  5729. }
  5730. *e = m->exponent * (SIGNED_VALUE)BASE_FIG;
  5731. *d *= VpGetSign(m);
  5732. Exit:
  5733. #ifdef BIGDECIMAL_DEBUG
  5734. if (gfDebug) {
  5735. VPrint(stdout, " VpVtoD: m=%\n", m);
  5736. printf(" d=%e * 10 **%ld\n", *d, *e);
  5737. printf(" BIGDECIMAL_DOUBLE_FIGURES = %d\n", BIGDECIMAL_DOUBLE_FIGURES);
  5738. }
  5739. #endif /*BIGDECIMAL_DEBUG */
  5740. return f;
  5741. }
  5742. /*
  5743. * m <- d
  5744. */
  5745. VP_EXPORT void
  5746. VpDtoV(Real *m, double d)
  5747. {
  5748. size_t ind_m, mm;
  5749. SIGNED_VALUE ne;
  5750. DECDIG i;
  5751. double val, val2;
  5752. if (isnan(d)) {
  5753. VpSetNaN(m);
  5754. goto Exit;
  5755. }
  5756. if (isinf(d)) {
  5757. if (d > 0.0) VpSetPosInf(m);
  5758. else VpSetNegInf(m);
  5759. goto Exit;
  5760. }
  5761. if (d == 0.0) {
  5762. VpSetZero(m, 1);
  5763. goto Exit;
  5764. }
  5765. val = (d > 0.) ? d : -d;
  5766. ne = 0;
  5767. if (val >= 1.0) {
  5768. while (val >= 1.0) {
  5769. val /= (double)BASE;
  5770. ++ne;
  5771. }
  5772. }
  5773. else {
  5774. val2 = 1.0 / (double)BASE;
  5775. while (val < val2) {
  5776. val *= (double)BASE;
  5777. --ne;
  5778. }
  5779. }
  5780. /* Now val = 0.xxxxx*BASE**ne */
  5781. mm = m->MaxPrec;
  5782. memset(m->frac, 0, mm * sizeof(DECDIG));
  5783. for (ind_m = 0; val > 0.0 && ind_m < mm; ind_m++) {
  5784. val *= (double)BASE;
  5785. i = (DECDIG)val;
  5786. val -= (double)i;
  5787. m->frac[ind_m] = i;
  5788. }
  5789. if (ind_m >= mm) ind_m = mm - 1;
  5790. VpSetSign(m, (d > 0.0) ? 1 : -1);
  5791. m->Prec = ind_m + 1;
  5792. m->exponent = ne;
  5793. VpInternalRound(m, 0, (m->Prec > 0) ? m->frac[m->Prec-1] : 0,
  5794. (DECDIG)(val*(double)BASE));
  5795. Exit:
  5796. #ifdef BIGDECIMAL_DEBUG
  5797. if (gfDebug) {
  5798. printf("VpDtoV d=%30.30e\n", d);
  5799. VPrint(stdout, " m=%\n", m);
  5800. }
  5801. #endif /* BIGDECIMAL_DEBUG */
  5802. return;
  5803. }
  5804. /*
  5805. * m <- ival
  5806. */
  5807. #if 0 /* unused */
  5808. VP_EXPORT void
  5809. VpItoV(Real *m, SIGNED_VALUE ival)
  5810. {
  5811. size_t mm, ind_m;
  5812. size_t val, v1, v2, v;
  5813. int isign;
  5814. SIGNED_VALUE ne;
  5815. if (ival == 0) {
  5816. VpSetZero(m, 1);
  5817. goto Exit;
  5818. }
  5819. isign = 1;
  5820. val = ival;
  5821. if (ival < 0) {
  5822. isign = -1;
  5823. val =(size_t)(-ival);
  5824. }
  5825. ne = 0;
  5826. ind_m = 0;
  5827. mm = m->MaxPrec;
  5828. while (ind_m < mm) {
  5829. m->frac[ind_m] = 0;
  5830. ++ind_m;
  5831. }
  5832. ind_m = 0;
  5833. while (val > 0) {
  5834. if (val) {
  5835. v1 = val;
  5836. v2 = 1;
  5837. while (v1 >= BASE) {
  5838. v1 /= BASE;
  5839. v2 *= BASE;
  5840. }
  5841. val = val - v2 * v1;
  5842. v = v1;
  5843. }
  5844. else {
  5845. v = 0;
  5846. }
  5847. m->frac[ind_m] = v;
  5848. ++ind_m;
  5849. ++ne;
  5850. }
  5851. m->Prec = ind_m - 1;
  5852. m->exponent = ne;
  5853. VpSetSign(m, isign);
  5854. VpNmlz(m);
  5855. Exit:
  5856. #ifdef BIGDECIMAL_DEBUG
  5857. if (gfDebug) {
  5858. printf(" VpItoV i=%d\n", ival);
  5859. VPrint(stdout, " m=%\n", m);
  5860. }
  5861. #endif /* BIGDECIMAL_DEBUG */
  5862. return;
  5863. }
  5864. #endif
  5865. /*
  5866. * y = SQRT(x), y*y - x =>0
  5867. */
  5868. VP_EXPORT int
  5869. VpSqrt(Real *y, Real *x)
  5870. {
  5871. Real *f = NULL;
  5872. Real *r = NULL;
  5873. size_t y_prec;
  5874. SIGNED_VALUE n, e;
  5875. SIGNED_VALUE prec;
  5876. ssize_t nr;
  5877. double val;
  5878. /* Zero or +Infinity ? */
  5879. if (VpIsZero(x) || VpIsPosInf(x)) {
  5880. VpAsgn(y,x,1);
  5881. goto Exit;
  5882. }
  5883. /* Negative ? */
  5884. if (BIGDECIMAL_NEGATIVE_P(x)) {
  5885. VpSetNaN(y);
  5886. return VpException(VP_EXCEPTION_OP, "sqrt of negative value", 0);
  5887. }
  5888. /* NaN ? */
  5889. if (VpIsNaN(x)) {
  5890. VpSetNaN(y);
  5891. return VpException(VP_EXCEPTION_OP, "sqrt of 'NaN'(Not a Number)", 0);
  5892. }
  5893. /* One ? */
  5894. if (VpIsOne(x)) {
  5895. VpSetOne(y);
  5896. goto Exit;
  5897. }
  5898. n = (SIGNED_VALUE)y->MaxPrec;
  5899. if (x->MaxPrec > (size_t)n) n = (ssize_t)x->MaxPrec;
  5900. /* allocate temporally variables */
  5901. f = VpAlloc(y->MaxPrec * (BASE_FIG + 2), "#1", 1, 1);
  5902. r = VpAlloc((n + n) * (BASE_FIG + 2), "#1", 1, 1);
  5903. nr = 0;
  5904. y_prec = y->MaxPrec;
  5905. prec = x->exponent - (ssize_t)y_prec;
  5906. if (x->exponent > 0)
  5907. ++prec;
  5908. else
  5909. --prec;
  5910. VpVtoD(&val, &e, x); /* val <- x */
  5911. e /= (SIGNED_VALUE)BASE_FIG;
  5912. n = e / 2;
  5913. if (e - n * 2 != 0) {
  5914. val /= BASE;
  5915. n = (e + 1) / 2;
  5916. }
  5917. VpDtoV(y, sqrt(val)); /* y <- sqrt(val) */
  5918. y->exponent += n;
  5919. n = (SIGNED_VALUE)roomof(BIGDECIMAL_DOUBLE_FIGURES, BASE_FIG);
  5920. y->MaxPrec = Min((size_t)n , y_prec);
  5921. f->MaxPrec = y->MaxPrec + 1;
  5922. n = (SIGNED_VALUE)(y_prec * BASE_FIG);
  5923. if (n < (SIGNED_VALUE)maxnr) n = (SIGNED_VALUE)maxnr;
  5924. do {
  5925. y->MaxPrec *= 2;
  5926. if (y->MaxPrec > y_prec) y->MaxPrec = y_prec;
  5927. f->MaxPrec = y->MaxPrec;
  5928. VpDivd(f, r, x, y); /* f = x/y */
  5929. VpAddSub(r, f, y, -1); /* r = f - y */
  5930. VpMult(f, VpPt5, r); /* f = 0.5*r */
  5931. if (VpIsZero(f)) goto converge;
  5932. VpAddSub(r, f, y, 1); /* r = y + f */
  5933. VpAsgn(y, r, 1); /* y = r */
  5934. } while (++nr < n);
  5935. #ifdef BIGDECIMAL_DEBUG
  5936. if (gfDebug) {
  5937. printf("ERROR(VpSqrt): did not converge within %ld iterations.\n", nr);
  5938. }
  5939. #endif /* BIGDECIMAL_DEBUG */
  5940. y->MaxPrec = y_prec;
  5941. converge:
  5942. VpChangeSign(y, 1);
  5943. #ifdef BIGDECIMAL_DEBUG
  5944. if (gfDebug) {
  5945. VpMult(r, y, y);
  5946. VpAddSub(f, x, r, -1);
  5947. printf("VpSqrt: iterations = %"PRIdSIZE"\n", nr);
  5948. VPrint(stdout, " y =% \n", y);
  5949. VPrint(stdout, " x =% \n", x);
  5950. VPrint(stdout, " x-y*y = % \n", f);
  5951. }
  5952. #endif /* BIGDECIMAL_DEBUG */
  5953. y->MaxPrec = y_prec;
  5954. Exit:
  5955. VpFree(f);
  5956. VpFree(r);
  5957. return 1;
  5958. }
  5959. /*
  5960. * Round relatively from the decimal point.
  5961. * f: rounding mode
  5962. * nf: digit location to round from the decimal point.
  5963. */
  5964. VP_EXPORT int
  5965. VpMidRound(Real *y, unsigned short f, ssize_t nf)
  5966. {
  5967. /* fracf: any positive digit under rounding position? */
  5968. /* fracf_1further: any positive digits under one further than the rounding position? */
  5969. /* exptoadd: number of digits needed to compensate negative nf */
  5970. int fracf, fracf_1further;
  5971. ssize_t n,i,ix,ioffset, exptoadd;
  5972. DECDIG v, shifter;
  5973. DECDIG div;
  5974. nf += y->exponent * (ssize_t)BASE_FIG;
  5975. exptoadd=0;
  5976. if (nf < 0) {
  5977. /* rounding position too left(large). */
  5978. if (f != VP_ROUND_CEIL && f != VP_ROUND_FLOOR) {
  5979. VpSetZero(y, VpGetSign(y)); /* truncate everything */
  5980. return 0;
  5981. }
  5982. exptoadd = -nf;
  5983. nf = 0;
  5984. }
  5985. ix = nf / (ssize_t)BASE_FIG;
  5986. if ((size_t)ix >= y->Prec) return 0; /* rounding position too right(small). */
  5987. v = y->frac[ix];
  5988. ioffset = nf - ix*(ssize_t)BASE_FIG;
  5989. n = (ssize_t)BASE_FIG - ioffset - 1;
  5990. for (shifter = 1, i = 0; i < n; ++i) shifter *= 10;
  5991. /* so the representation used (in y->frac) is an array of DECDIG, where
  5992. each DECDIG contains a value between 0 and BASE-1, consisting of BASE_FIG
  5993. decimal places.
  5994. (that numbers of decimal places are typed as ssize_t is somewhat confusing)
  5995. nf is now position (in decimal places) of the digit from the start of
  5996. the array.
  5997. ix is the position (in DECDIGs) of the DECDIG containing the decimal digit,
  5998. from the start of the array.
  5999. v is the value of this DECDIG
  6000. ioffset is the number of extra decimal places along of this decimal digit
  6001. within v.
  6002. n is the number of decimal digits remaining within v after this decimal digit
  6003. shifter is 10**n,
  6004. v % shifter are the remaining digits within v
  6005. v % (shifter * 10) are the digit together with the remaining digits within v
  6006. v / shifter are the digit's predecessors together with the digit
  6007. div = v / shifter / 10 is just the digit's precessors
  6008. (v / shifter) - div*10 is just the digit, which is what v ends up being reassigned to.
  6009. */
  6010. fracf = (v % (shifter * 10) > 0);
  6011. fracf_1further = ((v % shifter) > 0);
  6012. v /= shifter;
  6013. div = v / 10;
  6014. v = v - div*10;
  6015. /* now v is just the digit required.
  6016. now fracf is whether the digit or any of the remaining digits within v are non-zero
  6017. now fracf_1further is whether any of the remaining digits within v are non-zero
  6018. */
  6019. /* now check all the remaining DECDIGs for zero-ness a whole DECDIG at a time.
  6020. if we spot any non-zeroness, that means that we found a positive digit under
  6021. rounding position, and we also found a positive digit under one further than
  6022. the rounding position, so both searches (to see if any such non-zero digit exists)
  6023. can stop */
  6024. for (i = ix + 1; (size_t)i < y->Prec; i++) {
  6025. if (y->frac[i] % BASE) {
  6026. fracf = fracf_1further = 1;
  6027. break;
  6028. }
  6029. }
  6030. /* now fracf = does any positive digit exist under the rounding position?
  6031. now fracf_1further = does any positive digit exist under one further than the
  6032. rounding position?
  6033. now v = the first digit under the rounding position */
  6034. /* drop digits after pointed digit */
  6035. memset(y->frac + ix + 1, 0, (y->Prec - (ix + 1)) * sizeof(DECDIG));
  6036. switch (f) {
  6037. case VP_ROUND_DOWN: /* Truncate */
  6038. break;
  6039. case VP_ROUND_UP: /* Roundup */
  6040. if (fracf) ++div;
  6041. break;
  6042. case VP_ROUND_HALF_UP:
  6043. if (v>=5) ++div;
  6044. break;
  6045. case VP_ROUND_HALF_DOWN:
  6046. if (v > 5 || (v == 5 && fracf_1further)) ++div;
  6047. break;
  6048. case VP_ROUND_CEIL:
  6049. if (fracf && BIGDECIMAL_POSITIVE_P(y)) ++div;
  6050. break;
  6051. case VP_ROUND_FLOOR:
  6052. if (fracf && BIGDECIMAL_NEGATIVE_P(y)) ++div;
  6053. break;
  6054. case VP_ROUND_HALF_EVEN: /* Banker's rounding */
  6055. if (v > 5) ++div;
  6056. else if (v == 5) {
  6057. if (fracf_1further) {
  6058. ++div;
  6059. }
  6060. else {
  6061. if (ioffset == 0) {
  6062. /* v is the first decimal digit of its DECDIG;
  6063. need to grab the previous DECDIG if present
  6064. to check for evenness of the previous decimal
  6065. digit (which is same as that of the DECDIG since
  6066. base 10 has a factor of 2) */
  6067. if (ix && (y->frac[ix-1] % 2)) ++div;
  6068. }
  6069. else {
  6070. if (div % 2) ++div;
  6071. }
  6072. }
  6073. }
  6074. break;
  6075. }
  6076. for (i = 0; i <= n; ++i) div *= 10;
  6077. if (div >= BASE) {
  6078. if (ix) {
  6079. y->frac[ix] = 0;
  6080. VpRdup(y, ix);
  6081. }
  6082. else {
  6083. short s = VpGetSign(y);
  6084. SIGNED_VALUE e = y->exponent;
  6085. VpSetOne(y);
  6086. VpSetSign(y, s);
  6087. y->exponent = e + 1;
  6088. }
  6089. }
  6090. else {
  6091. y->frac[ix] = div;
  6092. VpNmlz(y);
  6093. }
  6094. if (exptoadd > 0) {
  6095. y->exponent += (SIGNED_VALUE)(exptoadd / BASE_FIG);
  6096. exptoadd %= (ssize_t)BASE_FIG;
  6097. for (i = 0; i < exptoadd; i++) {
  6098. y->frac[0] *= 10;
  6099. if (y->frac[0] >= BASE) {
  6100. y->frac[0] /= BASE;
  6101. y->exponent++;
  6102. }
  6103. }
  6104. }
  6105. return 1;
  6106. }
  6107. VP_EXPORT int
  6108. VpLeftRound(Real *y, unsigned short f, ssize_t nf)
  6109. /*
  6110. * Round from the left hand side of the digits.
  6111. */
  6112. {
  6113. DECDIG v;
  6114. if (!VpHasVal(y)) return 0; /* Unable to round */
  6115. v = y->frac[0];
  6116. nf -= VpExponent(y) * (ssize_t)BASE_FIG;
  6117. while ((v /= 10) != 0) nf--;
  6118. nf += (ssize_t)BASE_FIG-1;
  6119. return VpMidRound(y, f, nf);
  6120. }
  6121. VP_EXPORT int
  6122. VpActiveRound(Real *y, Real *x, unsigned short f, ssize_t nf)
  6123. {
  6124. /* First,assign whole value in truncation mode */
  6125. if (VpAsgn(y, x, 10) <= 1) return 0; /* Zero,NaN,or Infinity */
  6126. return VpMidRound(y, f, nf);
  6127. }
  6128. static int
  6129. VpLimitRound(Real *c, size_t ixDigit)
  6130. {
  6131. size_t ix = VpGetPrecLimit();
  6132. if (!VpNmlz(c)) return -1;
  6133. if (!ix) return 0;
  6134. if (!ixDigit) ixDigit = c->Prec-1;
  6135. if ((ix + BASE_FIG - 1) / BASE_FIG > ixDigit + 1) return 0;
  6136. return VpLeftRound(c, VpGetRoundMode(), (ssize_t)ix);
  6137. }
  6138. /* If I understand correctly, this is only ever used to round off the final decimal
  6139. digit of precision */
  6140. static void
  6141. VpInternalRound(Real *c, size_t ixDigit, DECDIG vPrev, DECDIG v)
  6142. {
  6143. int f = 0;
  6144. unsigned short const rounding_mode = VpGetRoundMode();
  6145. if (VpLimitRound(c, ixDigit)) return;
  6146. if (!v) return;
  6147. v /= BASE1;
  6148. switch (rounding_mode) {
  6149. case VP_ROUND_DOWN:
  6150. break;
  6151. case VP_ROUND_UP:
  6152. if (v) f = 1;
  6153. break;
  6154. case VP_ROUND_HALF_UP:
  6155. if (v >= 5) f = 1;
  6156. break;
  6157. case VP_ROUND_HALF_DOWN:
  6158. /* this is ok - because this is the last digit of precision,
  6159. the case where v == 5 and some further digits are nonzero
  6160. will never occur */
  6161. if (v >= 6) f = 1;
  6162. break;
  6163. case VP_ROUND_CEIL:
  6164. if (v && BIGDECIMAL_POSITIVE_P(c)) f = 1;
  6165. break;
  6166. case VP_ROUND_FLOOR:
  6167. if (v && BIGDECIMAL_NEGATIVE_P(c)) f = 1;
  6168. break;
  6169. case VP_ROUND_HALF_EVEN: /* Banker's rounding */
  6170. /* as per VP_ROUND_HALF_DOWN, because this is the last digit of precision,
  6171. there is no case to worry about where v == 5 and some further digits are nonzero */
  6172. if (v > 5) f = 1;
  6173. else if (v == 5 && vPrev % 2) f = 1;
  6174. break;
  6175. }
  6176. if (f) {
  6177. VpRdup(c, ixDigit);
  6178. VpNmlz(c);
  6179. }
  6180. }
  6181. /*
  6182. * Rounds up m(plus one to final digit of m).
  6183. */
  6184. static int
  6185. VpRdup(Real *m, size_t ind_m)
  6186. {
  6187. DECDIG carry;
  6188. if (!ind_m) ind_m = m->Prec;
  6189. carry = 1;
  6190. while (carry > 0 && ind_m--) {
  6191. m->frac[ind_m] += carry;
  6192. if (m->frac[ind_m] >= BASE) m->frac[ind_m] -= BASE;
  6193. else carry = 0;
  6194. }
  6195. if (carry > 0) { /* Overflow,count exponent and set fraction part be 1 */
  6196. if (!AddExponent(m, 1)) return 0;
  6197. m->Prec = m->frac[0] = 1;
  6198. }
  6199. else {
  6200. VpNmlz(m);
  6201. }
  6202. return 1;
  6203. }
  6204. /*
  6205. * y = x - fix(x)
  6206. */
  6207. VP_EXPORT void
  6208. VpFrac(Real *y, Real *x)
  6209. {
  6210. size_t my, ind_y, ind_x;
  6211. if (!VpHasVal(x)) {
  6212. VpAsgn(y, x, 1);
  6213. goto Exit;
  6214. }
  6215. if (x->exponent > 0 && (size_t)x->exponent >= x->Prec) {
  6216. VpSetZero(y, VpGetSign(x));
  6217. goto Exit;
  6218. }
  6219. else if (x->exponent <= 0) {
  6220. VpAsgn(y, x, 1);
  6221. goto Exit;
  6222. }
  6223. /* satisfy: x->exponent > 0 */
  6224. y->Prec = x->Prec - (size_t)x->exponent;
  6225. y->Prec = Min(y->Prec, y->MaxPrec);
  6226. y->exponent = 0;
  6227. VpSetSign(y, VpGetSign(x));
  6228. ind_y = 0;
  6229. my = y->Prec;
  6230. ind_x = x->exponent;
  6231. while (ind_y < my) {
  6232. y->frac[ind_y] = x->frac[ind_x];
  6233. ++ind_y;
  6234. ++ind_x;
  6235. }
  6236. VpNmlz(y);
  6237. Exit:
  6238. #ifdef BIGDECIMAL_DEBUG
  6239. if (gfDebug) {
  6240. VPrint(stdout, "VpFrac y=%\n", y);
  6241. VPrint(stdout, " x=%\n", x);
  6242. }
  6243. #endif /* BIGDECIMAL_DEBUG */
  6244. return;
  6245. }
  6246. /*
  6247. * y = x ** n
  6248. */
  6249. VP_EXPORT int
  6250. VpPowerByInt(Real *y, Real *x, SIGNED_VALUE n)
  6251. {
  6252. size_t s, ss;
  6253. ssize_t sign;
  6254. Real *w1 = NULL;
  6255. Real *w2 = NULL;
  6256. if (VpIsZero(x)) {
  6257. if (n == 0) {
  6258. VpSetOne(y);
  6259. goto Exit;
  6260. }
  6261. sign = VpGetSign(x);
  6262. if (n < 0) {
  6263. n = -n;
  6264. if (sign < 0) sign = (n % 2) ? -1 : 1;
  6265. VpSetInf(y, sign);
  6266. }
  6267. else {
  6268. if (sign < 0) sign = (n % 2) ? -1 : 1;
  6269. VpSetZero(y,sign);
  6270. }
  6271. goto Exit;
  6272. }
  6273. if (VpIsNaN(x)) {
  6274. VpSetNaN(y);
  6275. goto Exit;
  6276. }
  6277. if (VpIsInf(x)) {
  6278. if (n == 0) {
  6279. VpSetOne(y);
  6280. goto Exit;
  6281. }
  6282. if (n > 0) {
  6283. VpSetInf(y, (n % 2 == 0 || VpIsPosInf(x)) ? 1 : -1);
  6284. goto Exit;
  6285. }
  6286. VpSetZero(y, (n % 2 == 0 || VpIsPosInf(x)) ? 1 : -1);
  6287. goto Exit;
  6288. }
  6289. if (x->exponent == 1 && x->Prec == 1 && x->frac[0] == 1) {
  6290. /* abs(x) = 1 */
  6291. VpSetOne(y);
  6292. if (BIGDECIMAL_POSITIVE_P(x)) goto Exit;
  6293. if ((n % 2) == 0) goto Exit;
  6294. VpSetSign(y, -1);
  6295. goto Exit;
  6296. }
  6297. if (n > 0) sign = 1;
  6298. else if (n < 0) {
  6299. sign = -1;
  6300. n = -n;
  6301. }
  6302. else {
  6303. VpSetOne(y);
  6304. goto Exit;
  6305. }
  6306. /* Allocate working variables */
  6307. w1 = VpAlloc((y->MaxPrec + 2) * BASE_FIG, "#0", 1, 1);
  6308. w2 = VpAlloc((w1->MaxPrec * 2 + 1) * BASE_FIG, "#0", 1, 1);
  6309. /* calculation start */
  6310. VpAsgn(y, x, 1);
  6311. --n;
  6312. while (n > 0) {
  6313. VpAsgn(w1, x, 1);
  6314. s = 1;
  6315. while (ss = s, (s += s) <= (size_t)n) {
  6316. VpMult(w2, w1, w1);
  6317. VpAsgn(w1, w2, 1);
  6318. }
  6319. n -= (SIGNED_VALUE)ss;
  6320. VpMult(w2, y, w1);
  6321. VpAsgn(y, w2, 1);
  6322. }
  6323. if (sign < 0) {
  6324. VpDivd(w1, w2, VpConstOne, y);
  6325. VpAsgn(y, w1, 1);
  6326. }
  6327. Exit:
  6328. #ifdef BIGDECIMAL_DEBUG
  6329. if (gfDebug) {
  6330. VPrint(stdout, "VpPowerByInt y=%\n", y);
  6331. VPrint(stdout, "VpPowerByInt x=%\n", x);
  6332. printf(" n=%"PRIdVALUE"\n", n);
  6333. }
  6334. #endif /* BIGDECIMAL_DEBUG */
  6335. VpFree(w2);
  6336. VpFree(w1);
  6337. return 1;
  6338. }
  6339. #ifdef BIGDECIMAL_DEBUG
  6340. int
  6341. VpVarCheck(Real * v)
  6342. /*
  6343. * Checks the validity of the Real variable v.
  6344. * [Input]
  6345. * v ... Real *, variable to be checked.
  6346. * [Returns]
  6347. * 0 ... correct v.
  6348. * other ... error
  6349. */
  6350. {
  6351. size_t i;
  6352. if (v->MaxPrec == 0) {
  6353. printf("ERROR(VpVarCheck): Illegal Max. Precision(=%"PRIuSIZE")\n",
  6354. v->MaxPrec);
  6355. return 1;
  6356. }
  6357. if (v->Prec == 0 || v->Prec > v->MaxPrec) {
  6358. printf("ERROR(VpVarCheck): Illegal Precision(=%"PRIuSIZE")\n", v->Prec);
  6359. printf(" Max. Prec.=%"PRIuSIZE"\n", v->MaxPrec);
  6360. return 2;
  6361. }
  6362. for (i = 0; i < v->Prec; ++i) {
  6363. if (v->frac[i] >= BASE) {
  6364. printf("ERROR(VpVarCheck): Illegal fraction\n");
  6365. printf(" Frac[%"PRIuSIZE"]=%"PRIuDECDIG"\n", i, v->frac[i]);
  6366. printf(" Prec. =%"PRIuSIZE"\n", v->Prec);
  6367. printf(" Exp. =%"PRIdVALUE"\n", v->exponent);
  6368. printf(" BASE =%"PRIuDECDIG"\n", BASE);
  6369. return 3;
  6370. }
  6371. }
  6372. return 0;
  6373. }
  6374. #endif /* BIGDECIMAL_DEBUG */