dec.go 14 KB

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