dec.go 15 KB

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