dec.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. // Package inf (type inf.Dec) implements "infinite-precision" decimal
  2. // arithmetic.
  3. // "Infinite precision" describes two characteristics: practically unlimited
  4. // precision for decimal number representation and no support for calculating
  5. // with any specific fixed precision.
  6. // (Although there is no practical limit on precision, inf.Dec can only
  7. // represent finite decimals.)
  8. //
  9. // This package is currently in experimental stage and the API may change.
  10. //
  11. // This package does NOT support:
  12. // - rounding to specific precisions (as opposed to specific decimal positions)
  13. // - the notion of context (each rounding must be explicit)
  14. // - NaN and Inf values, and distinguishing between positive and negative zero
  15. // - conversions to and from float32/64 types
  16. //
  17. // Features considered for possible addition:
  18. // + formatting options
  19. // + Exp method
  20. // + combined operations such as AddRound/MulAdd etc
  21. // + exchanging data in decimal32/64/128 formats
  22. //
  23. package inf
  24. // TODO:
  25. // - avoid excessive deep copying (quo and rounders)
  26. import (
  27. "fmt"
  28. "io"
  29. "math/big"
  30. "strings"
  31. )
  32. // A Dec represents a signed arbitrary-precision decimal.
  33. // It is a combination of a sign, an arbitrary-precision integer coefficient
  34. // value, and a signed fixed-precision exponent value.
  35. // The sign and the coefficient value are handled together as a signed value
  36. // and referred to as the unscaled value.
  37. // (Positive and negative zero values are not distinguished.)
  38. // Since the exponent is most commonly non-positive, it is handled in negated
  39. // form and referred to as scale.
  40. //
  41. // The mathematical value of a Dec equals:
  42. //
  43. // unscaled * 10**(-scale)
  44. //
  45. // Note that different Dec representations may have equal mathematical values.
  46. //
  47. // unscaled scale String()
  48. // -------------------------
  49. // 0 0 "0"
  50. // 0 2 "0.00"
  51. // 0 -2 "0"
  52. // 1 0 "1"
  53. // 100 2 "1.00"
  54. // 10 0 "10"
  55. // 1 -1 "10"
  56. //
  57. // The zero value for a Dec represents the value 0 with scale 0.
  58. //
  59. // Operations are typically performed through the *Dec type.
  60. // The semantics of the assignment operation "=" for "bare" Dec values is
  61. // undefined and should not be relied on.
  62. //
  63. // Methods are typically of the form:
  64. //
  65. // func (z *Dec) Op(x, y *Dec) *Dec
  66. //
  67. // and implement operations z = x Op y with the result as receiver; if it
  68. // is one of the operands it may be overwritten (and its memory reused).
  69. // To enable chaining of operations, the result is also returned. Methods
  70. // returning a result other than *Dec take one of the operands as the receiver.
  71. //
  72. // A "bare" Quo method (quotient / division operation) is not provided, as the
  73. // result is not always a finite decimal and thus in general cannot be
  74. // represented as a Dec.
  75. // Instead, in the common case when rounding is (potentially) necessary,
  76. // QuoRound should be used with a Scale and a Rounder.
  77. // QuoExact or QuoRound with RoundExact can be used in the special cases when it
  78. // is known that the result is always a finite decimal.
  79. //
  80. type Dec struct {
  81. unscaled big.Int
  82. scale Scale
  83. }
  84. // Scale represents the type used for the scale of a Dec.
  85. type Scale int32
  86. const scaleSize = 4 // bytes in a Scale value
  87. // Scaler represents a method for obtaining the scale to use for the result of
  88. // an operation on x and y.
  89. type scaler interface {
  90. Scale(x *Dec, y *Dec) Scale
  91. }
  92. var bigInt = [...]*big.Int{
  93. big.NewInt(0), big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4),
  94. big.NewInt(5), big.NewInt(6), big.NewInt(7), big.NewInt(8), big.NewInt(9),
  95. big.NewInt(10),
  96. }
  97. var exp10cache [64]big.Int = func() [64]big.Int {
  98. e10, e10i := [64]big.Int{}, bigInt[1]
  99. for i, _ := range e10 {
  100. e10[i].Set(e10i)
  101. e10i = new(big.Int).Mul(e10i, bigInt[10])
  102. }
  103. return e10
  104. }()
  105. // NewDec allocates and returns a new Dec set to the given int64 unscaled value
  106. // and scale.
  107. func NewDec(unscaled int64, scale Scale) *Dec {
  108. return new(Dec).SetUnscaled(unscaled).SetScale(scale)
  109. }
  110. // NewDecBig allocates and returns a new Dec set to the given *big.Int unscaled
  111. // value and scale.
  112. func NewDecBig(unscaled *big.Int, scale Scale) *Dec {
  113. return new(Dec).SetUnscaledBig(unscaled).SetScale(scale)
  114. }
  115. // Scale returns the scale of x.
  116. func (x *Dec) Scale() Scale {
  117. return x.scale
  118. }
  119. // Unscaled returns the unscaled value of x for u and true for ok when the
  120. // unscaled value can be represented as int64; otherwise it returns an undefined
  121. // int64 value for u and false for ok. Use x.UnscaledBig().Int64() to avoid
  122. // checking the validity of the value when the check is known to be redundant.
  123. func (x *Dec) Unscaled() (u int64, ok bool) {
  124. u = x.unscaled.Int64()
  125. var i big.Int
  126. ok = i.SetInt64(u).Cmp(&x.unscaled) == 0
  127. return
  128. }
  129. // UnscaledBig returns the unscaled value of x as *big.Int.
  130. func (x *Dec) UnscaledBig() *big.Int {
  131. return &x.unscaled
  132. }
  133. // SetScale sets the scale of z, with the unscaled value unchanged, and returns
  134. // z.
  135. // The mathematical value of the Dec changes as if it was multiplied by
  136. // 10**(oldscale-scale).
  137. func (z *Dec) SetScale(scale Scale) *Dec {
  138. z.scale = scale
  139. return z
  140. }
  141. // SetUnscaled sets the unscaled value of z, with the scale unchanged, and
  142. // returns z.
  143. func (z *Dec) SetUnscaled(unscaled int64) *Dec {
  144. z.unscaled.SetInt64(unscaled)
  145. return z
  146. }
  147. // SetUnscaledBig sets the unscaled value of z, with the scale unchanged, and
  148. // returns z.
  149. func (z *Dec) SetUnscaledBig(unscaled *big.Int) *Dec {
  150. z.unscaled.Set(unscaled)
  151. return z
  152. }
  153. // Set sets z to the value of x and returns z.
  154. // It does nothing if z == x.
  155. func (z *Dec) Set(x *Dec) *Dec {
  156. if z != x {
  157. z.SetUnscaledBig(x.UnscaledBig())
  158. z.SetScale(x.Scale())
  159. }
  160. return z
  161. }
  162. // Sign returns:
  163. //
  164. // -1 if x < 0
  165. // 0 if x == 0
  166. // +1 if x > 0
  167. //
  168. func (x *Dec) Sign() int {
  169. return x.UnscaledBig().Sign()
  170. }
  171. // Neg sets z to -x and returns z.
  172. func (z *Dec) Neg(x *Dec) *Dec {
  173. z.SetScale(x.Scale())
  174. z.UnscaledBig().Neg(x.UnscaledBig())
  175. return z
  176. }
  177. // Cmp compares x and y and returns:
  178. //
  179. // -1 if x < y
  180. // 0 if x == y
  181. // +1 if x > y
  182. //
  183. func (x *Dec) Cmp(y *Dec) int {
  184. xx, yy := upscale(x, y)
  185. return xx.UnscaledBig().Cmp(yy.UnscaledBig())
  186. }
  187. // Abs sets z to |x| (the absolute value of x) and returns z.
  188. func (z *Dec) Abs(x *Dec) *Dec {
  189. z.SetScale(x.Scale())
  190. z.UnscaledBig().Abs(x.UnscaledBig())
  191. return z
  192. }
  193. // Add sets z to the sum x+y and returns z.
  194. // The scale of z is the greater of the scales of x and y.
  195. func (z *Dec) Add(x, y *Dec) *Dec {
  196. xx, yy := upscale(x, y)
  197. z.SetScale(xx.Scale())
  198. z.UnscaledBig().Add(xx.UnscaledBig(), yy.UnscaledBig())
  199. return z
  200. }
  201. // Sub sets z to the difference x-y and returns z.
  202. // The scale of z is the greater of the scales of x and y.
  203. func (z *Dec) Sub(x, y *Dec) *Dec {
  204. xx, yy := upscale(x, y)
  205. z.SetScale(xx.Scale())
  206. z.UnscaledBig().Sub(xx.UnscaledBig(), yy.UnscaledBig())
  207. return z
  208. }
  209. // Mul sets z to the product x*y and returns z.
  210. // The scale of z is the sum of the scales of x and y.
  211. func (z *Dec) Mul(x, y *Dec) *Dec {
  212. z.SetScale(x.Scale() + y.Scale())
  213. z.UnscaledBig().Mul(x.UnscaledBig(), y.UnscaledBig())
  214. return z
  215. }
  216. // Round sets z to the value of x rounded to Scale s using Rounder r, and
  217. // returns z.
  218. func (z *Dec) Round(x *Dec, s Scale, r Rounder) *Dec {
  219. return z.QuoRound(x, NewDec(1, 0), s, r)
  220. }
  221. // QuoRound sets z to the quotient x/y, rounded using the given Rounder to the
  222. // specified scale.
  223. //
  224. // If the rounder is RoundExact but the result can not be expressed exactly at
  225. // the specified scale, QuoRound returns nil, and the value of z is undefined.
  226. //
  227. // There is no corresponding Div method; the equivalent can be achieved through
  228. // the choice of Rounder used.
  229. //
  230. func (z *Dec) QuoRound(x, y *Dec, s Scale, r Rounder) *Dec {
  231. return z.quo(x, y, sclr{s}, r)
  232. }
  233. func (z *Dec) quo(x, y *Dec, s scaler, r Rounder) *Dec {
  234. scl := s.Scale(x, y)
  235. var zzz *Dec
  236. if r.UseRemainder() {
  237. zz, rA, rB := new(Dec).quoRem(x, y, scl, true, new(big.Int), new(big.Int))
  238. zzz = r.Round(new(Dec), zz, rA, rB)
  239. } else {
  240. zz, _, _ := new(Dec).quoRem(x, y, scl, false, nil, nil)
  241. zzz = r.Round(new(Dec), zz, nil, nil)
  242. }
  243. if zzz == nil {
  244. return nil
  245. }
  246. return z.Set(zzz)
  247. }
  248. // QuoExact sets z to the quotient x/y and returns z when x/y is a finite
  249. // decimal. Otherwise it returns nil and the value of z is undefined.
  250. //
  251. // The scale of a non-nil result is "x.Scale() - y.Scale()" or greater; it is
  252. // calculated so that the remainder will be zero whenever x/y is a finite
  253. // decimal.
  254. func (z *Dec) QuoExact(x, y *Dec) *Dec {
  255. return z.quo(x, y, scaleQuoExact{}, RoundExact)
  256. }
  257. // quoRem sets z to the quotient x/y with the scale s, and if useRem is true,
  258. // it sets remNum and remDen to the numerator and denominator of the remainder.
  259. // It returns z, remNum and remDen.
  260. //
  261. // The remainder is normalized to the range -1 < r < 1 to simplify rounding;
  262. // that is, the results satisfy the following equation:
  263. //
  264. // x / y = z + (remNum/remDen) * 10**(-z.Scale())
  265. //
  266. // See Rounder for more details about rounding.
  267. //
  268. func (z *Dec) quoRem(x, y *Dec, s Scale, useRem bool,
  269. remNum, remDen *big.Int) (*Dec, *big.Int, *big.Int) {
  270. // difference (required adjustment) compared to "canonical" result scale
  271. shift := s - (x.Scale() - y.Scale())
  272. // pointers to adjusted unscaled dividend and divisor
  273. var ix, iy *big.Int
  274. switch {
  275. case shift > 0:
  276. // increased scale: decimal-shift dividend left
  277. ix = new(big.Int).Mul(x.UnscaledBig(), exp10(shift))
  278. iy = y.UnscaledBig()
  279. case shift < 0:
  280. // decreased scale: decimal-shift divisor left
  281. ix = x.UnscaledBig()
  282. iy = new(big.Int).Mul(y.UnscaledBig(), exp10(-shift))
  283. default:
  284. ix = x.UnscaledBig()
  285. iy = y.UnscaledBig()
  286. }
  287. // save a copy of iy in case it to be overwritten with the result
  288. iy2 := iy
  289. if iy == z.UnscaledBig() {
  290. iy2 = new(big.Int).Set(iy)
  291. }
  292. // set scale
  293. z.SetScale(s)
  294. // set unscaled
  295. if useRem {
  296. // Int division
  297. _, intr := z.UnscaledBig().QuoRem(ix, iy, new(big.Int))
  298. // set remainder
  299. remNum.Set(intr)
  300. remDen.Set(iy2)
  301. } else {
  302. z.UnscaledBig().Quo(ix, iy)
  303. }
  304. return z, remNum, remDen
  305. }
  306. type sclr struct{ s Scale }
  307. func (s sclr) Scale(x, y *Dec) Scale {
  308. return s.s
  309. }
  310. type scaleQuoExact struct{}
  311. func (sqe scaleQuoExact) Scale(x, y *Dec) Scale {
  312. rem := new(big.Rat).SetFrac(x.UnscaledBig(), y.UnscaledBig())
  313. f2, f5 := factor2(rem.Denom()), factor(rem.Denom(), bigInt[5])
  314. var f10 Scale
  315. if f2 > f5 {
  316. f10 = Scale(f2)
  317. } else {
  318. f10 = Scale(f5)
  319. }
  320. return x.Scale() - y.Scale() + f10
  321. }
  322. func factor(n *big.Int, p *big.Int) int {
  323. // could be improved for large factors
  324. d, f := n, 0
  325. for {
  326. dd, dm := new(big.Int).DivMod(d, p, new(big.Int))
  327. if dm.Sign() == 0 {
  328. f++
  329. d = dd
  330. } else {
  331. break
  332. }
  333. }
  334. return f
  335. }
  336. func factor2(n *big.Int) int {
  337. // could be improved for large factors
  338. f := 0
  339. for ; n.Bit(f) == 0; f++ {
  340. }
  341. return f
  342. }
  343. func upscale(a, b *Dec) (*Dec, *Dec) {
  344. if a.Scale() == b.Scale() {
  345. return a, b
  346. }
  347. if a.Scale() > b.Scale() {
  348. bb := b.rescale(a.Scale())
  349. return a, bb
  350. }
  351. aa := a.rescale(b.Scale())
  352. return aa, b
  353. }
  354. func exp10(x Scale) *big.Int {
  355. if int(x) < len(exp10cache) {
  356. return &exp10cache[int(x)]
  357. }
  358. return new(big.Int).Exp(bigInt[10], big.NewInt(int64(x)), nil)
  359. }
  360. func (x *Dec) rescale(newScale Scale) *Dec {
  361. shift := newScale - x.Scale()
  362. switch {
  363. case shift < 0:
  364. e := exp10(-shift)
  365. return NewDecBig(new(big.Int).Quo(x.UnscaledBig(), e), newScale)
  366. case shift > 0:
  367. e := exp10(shift)
  368. return NewDecBig(new(big.Int).Mul(x.UnscaledBig(), e), newScale)
  369. }
  370. return x
  371. }
  372. var zeros = []byte("00000000000000000000000000000000" +
  373. "00000000000000000000000000000000")
  374. var lzeros = Scale(len(zeros))
  375. func appendZeros(s []byte, n Scale) []byte {
  376. for i := Scale(0); i < n; i += lzeros {
  377. if n > i+lzeros {
  378. s = append(s, zeros...)
  379. } else {
  380. s = append(s, zeros[0:n-i]...)
  381. }
  382. }
  383. return s
  384. }
  385. func (x *Dec) String() string {
  386. if x == nil {
  387. return "<nil>"
  388. }
  389. scale := x.Scale()
  390. s := []byte(x.UnscaledBig().String())
  391. if scale <= 0 {
  392. if scale != 0 && x.unscaled.Sign() != 0 {
  393. s = appendZeros(s, -scale)
  394. }
  395. return string(s)
  396. }
  397. negbit := Scale(-((x.Sign() - 1) / 2))
  398. // scale > 0
  399. lens := Scale(len(s))
  400. if lens-negbit <= scale {
  401. ss := make([]byte, 0, scale+2)
  402. if negbit == 1 {
  403. ss = append(ss, '-')
  404. }
  405. ss = append(ss, '0', '.')
  406. ss = appendZeros(ss, scale-lens+negbit)
  407. ss = append(ss, s[negbit:]...)
  408. return string(ss)
  409. }
  410. // lens > scale
  411. ss := make([]byte, 0, lens+1)
  412. ss = append(ss, s[:lens-scale]...)
  413. ss = append(ss, '.')
  414. ss = append(ss, s[lens-scale:]...)
  415. return string(ss)
  416. }
  417. // Format is a support routine for fmt.Formatter. It accepts the decimal
  418. // formats 'd' and 'f', and handles both equivalently.
  419. // Width, precision, flags and bases 2, 8, 16 are not supported.
  420. func (x *Dec) Format(s fmt.State, ch rune) {
  421. if ch != 'd' && ch != 'f' && ch != 'v' && ch != 's' {
  422. fmt.Fprintf(s, "%%!%c(dec.Dec=%s)", ch, x.String())
  423. return
  424. }
  425. fmt.Fprintf(s, x.String())
  426. }
  427. func (z *Dec) scan(r io.RuneScanner) (*Dec, error) {
  428. unscaled := make([]byte, 0, 256) // collects chars of unscaled as bytes
  429. dp, dg := -1, -1 // indexes of decimal point, first digit
  430. loop:
  431. for {
  432. ch, _, err := r.ReadRune()
  433. if err == io.EOF {
  434. break loop
  435. }
  436. if err != nil {
  437. return nil, err
  438. }
  439. switch {
  440. case ch == '+' || ch == '-':
  441. if len(unscaled) > 0 || dp >= 0 { // must be first character
  442. r.UnreadRune()
  443. break loop
  444. }
  445. case ch == '.':
  446. if dp >= 0 {
  447. r.UnreadRune()
  448. break loop
  449. }
  450. dp = len(unscaled)
  451. continue // don't add to unscaled
  452. case ch >= '0' && ch <= '9':
  453. if dg == -1 {
  454. dg = len(unscaled)
  455. }
  456. default:
  457. r.UnreadRune()
  458. break loop
  459. }
  460. unscaled = append(unscaled, byte(ch))
  461. }
  462. if dg == -1 {
  463. return nil, fmt.Errorf("no digits read")
  464. }
  465. if dp >= 0 {
  466. z.SetScale(Scale(len(unscaled) - dp))
  467. } else {
  468. z.SetScale(0)
  469. }
  470. _, ok := z.UnscaledBig().SetString(string(unscaled), 10)
  471. if !ok {
  472. return nil, fmt.Errorf("invalid decimal: %s", string(unscaled))
  473. }
  474. return z, nil
  475. }
  476. // SetString sets z to the value of s, interpreted as a decimal (base 10),
  477. // and returns z and a boolean indicating success. The scale of z is the
  478. // number of digits after the decimal point (including any trailing 0s),
  479. // or 0 if there is no decimal point. If SetString fails, the value of z
  480. // is undefined but the returned value is nil.
  481. func (z *Dec) SetString(s string) (*Dec, bool) {
  482. r := strings.NewReader(s)
  483. _, err := z.scan(r)
  484. if err != nil {
  485. return nil, false
  486. }
  487. _, _, err = r.ReadRune()
  488. if err != io.EOF {
  489. return nil, false
  490. }
  491. // err == io.EOF => scan consumed all of s
  492. return z, true
  493. }
  494. // Scan is a support routine for fmt.Scanner; it sets z to the value of
  495. // the scanned number. It accepts the decimal formats 'd' and 'f', and
  496. // handles both equivalently. Bases 2, 8, 16 are not supported.
  497. // The scale of z is the number of digits after the decimal point
  498. // (including any trailing 0s), or 0 if there is no decimal point.
  499. func (z *Dec) Scan(s fmt.ScanState, ch rune) error {
  500. if ch != 'd' && ch != 'f' && ch != 's' && ch != 'v' {
  501. return fmt.Errorf("Dec.Scan: invalid verb '%c'", ch)
  502. }
  503. s.SkipSpace()
  504. _, err := z.scan(s)
  505. return err
  506. }
  507. // Gob encoding version
  508. const decGobVersion byte = 1
  509. func scaleBytes(s Scale) []byte {
  510. buf := make([]byte, scaleSize)
  511. i := scaleSize
  512. for j := 0; j < scaleSize; j++ {
  513. i--
  514. buf[i] = byte(s)
  515. s >>= 8
  516. }
  517. return buf
  518. }
  519. func scale(b []byte) (s Scale) {
  520. for j := 0; j < scaleSize; j++ {
  521. s <<= 8
  522. s |= Scale(b[j])
  523. }
  524. return
  525. }
  526. // GobEncode implements the gob.GobEncoder interface.
  527. func (x *Dec) GobEncode() ([]byte, error) {
  528. buf, err := x.UnscaledBig().GobEncode()
  529. if err != nil {
  530. return nil, err
  531. }
  532. buf = append(append(buf, scaleBytes(x.Scale())...), decGobVersion)
  533. return buf, nil
  534. }
  535. // GobDecode implements the gob.GobDecoder interface.
  536. func (z *Dec) GobDecode(buf []byte) error {
  537. if len(buf) == 0 {
  538. return fmt.Errorf("Dec.GobDecode: no data")
  539. }
  540. b := buf[len(buf)-1]
  541. if b != decGobVersion {
  542. return fmt.Errorf("Dec.GobDecode: encoding version %d not supported", b)
  543. }
  544. l := len(buf) - scaleSize - 1
  545. err := z.UnscaledBig().GobDecode(buf[:l])
  546. if err != nil {
  547. return err
  548. }
  549. z.SetScale(scale(buf[l : l+scaleSize]))
  550. return nil
  551. }
  552. // MarshalText implements the encoding.TextMarshaler interface.
  553. func (x *Dec) MarshalText() ([]byte, error) {
  554. return []byte(x.String()), nil
  555. }
  556. // UnmarshalText implements the encoding.TextUnmarshaler interface.
  557. func (z *Dec) UnmarshalText(data []byte) error {
  558. _, ok := z.SetString(string(data))
  559. if !ok {
  560. return fmt.Errorf("invalid inf.Dec")
  561. }
  562. return nil
  563. }