dec.go 15 KB

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