dec.go 15 KB

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