dec.go 15 KB

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