dec.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. // + exchanging data in decimal32/64/128 formats
  21. //
  22. // Methods are typically of the form:
  23. //
  24. // func (z *Dec) Op(x, y *Dec) *Dec
  25. //
  26. // and implement operations z = x Op y with the result as receiver; if it
  27. // is one of the operands it may be overwritten (and its memory reused).
  28. // To enable chaining of operations, the result is also returned. Methods
  29. // returning a result other than *Dec take one of the operands as the receiver.
  30. //
  31. // Quotient (division) operation uses Scalers and Rounders to specify the
  32. // desired behavior. See Quo, Scaler, and Rounder for details.
  33. //
  34. package inf
  35. import (
  36. "fmt"
  37. "io"
  38. "math/big"
  39. "strings"
  40. )
  41. // A Dec represents a signed arbitrary-precision decimal.
  42. // It is a combination of a sign, an arbitrary-precision integer coefficient
  43. // value, and a signed fixed-precision exponent value.
  44. // The sign and the coefficient value are handled together as a signed value
  45. // and referred to as the unscaled value.
  46. // (Positive and negative zero values are not distinguished.)
  47. // Since the exponent is most commonly negative, it is handled in negated form
  48. // and referred to as scale.
  49. //
  50. // The mathematical value of a Dec equals:
  51. //
  52. // unscaled * 10**(-scale)
  53. //
  54. // Note that different Dec representations may have equal mathematical values.
  55. //
  56. // unscaled scale String()
  57. // -------------------------
  58. // 0 0 "0"
  59. // 0 2 "0.00"
  60. // 0 -2 "0"
  61. // 1 0 "1"
  62. // 100 2 "1.00"
  63. // 10 0 "10"
  64. // 1 -1 "10"
  65. //
  66. // The zero value for a Dec represents the value 0 with scale 0.
  67. //
  68. type Dec struct {
  69. unscaled big.Int
  70. scale Scale
  71. }
  72. // Scale represents the type used for the scale of a Dec.
  73. type Scale int32
  74. const scaleSize = 4 // bytes in a Scale value
  75. // Scaler represents a method for obtaining the scale to use for the result of
  76. // an operation on x and y.
  77. type Scaler interface {
  78. Scale(x *Dec, y *Dec) Scale
  79. }
  80. // Scale() for a Scale value always returns the Scale value. This allows a Scale
  81. // value to be used as a Scaler when the desired scale is independent of the
  82. // values x and y.
  83. func (s Scale) Scale(x *Dec, y *Dec) Scale {
  84. return s
  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.Quo(x, NewDecInt64(1), s, r)
  206. }
  207. // Quo sets z to the quotient x/y, with the scale obtained from the given
  208. // Scaler, rounded using the given Rounder.
  209. // If the result from the rounder is nil, Quo also returns nil, and the value
  210. // of z is undefined.
  211. //
  212. // There is no corresponding Div method; the equivalent can be achieved through
  213. // the choice of Rounder used.
  214. //
  215. // See Rounder for details on the various ways for rounding.
  216. func (z *Dec) Quo(x, y *Dec, scaler Scaler, rounder Rounder) *Dec {
  217. s := scaler.Scale(x, y)
  218. var zzz *Dec
  219. if rounder.UseRemainder() {
  220. zz, rA, rB := new(Dec).quoRem(x, y, s, true, new(big.Int), new(big.Int))
  221. zzz = rounder.Round(new(Dec), zz, rA, rB)
  222. } else {
  223. zz, _, _ := new(Dec).quoRem(x, y, s, false, nil, nil)
  224. zzz = rounder.Round(new(Dec), zz, nil, nil)
  225. }
  226. if zzz == nil {
  227. return nil
  228. }
  229. return z.move(zzz)
  230. }
  231. // QuoExact(x, y) is a shorthand for Quo(x, y, ScaleQuoExact, RoundExact).
  232. // If x/y can be expressed as a Dec without rounding, QuoExact sets z to the
  233. // quotient x/y and returns z. Otherwise, it returns nil and the value of z is
  234. // undefined.
  235. func (z *Dec) QuoExact(x, y *Dec) *Dec {
  236. return z.Quo(x, y, ScaleQuoExact, RoundExact)
  237. }
  238. // quoRem sets z to the quotient x/y with the scale s, and if useRem is true,
  239. // it sets remNum and remDen to the numerator and denominator of the remainder.
  240. // It returns z, remNum and remDen.
  241. //
  242. // The remainder is normalized to the range -1 < r < 1 to simplify rounding;
  243. // that is, the results satisfy the following equation:
  244. //
  245. // x / y = z + (remNum/remDen) * 10**(-z.Scale())
  246. //
  247. // See Rounder for more details about rounding.
  248. //
  249. func (z *Dec) quoRem(x, y *Dec, s Scale, useRem bool,
  250. remNum, remDen *big.Int) (*Dec, *big.Int, *big.Int) {
  251. // difference (required adjustment) compared to "canonical" result scale
  252. shift := s - (x.Scale() - y.Scale())
  253. // pointers to adjusted unscaled dividend and divisor
  254. var ix, iy *big.Int
  255. switch {
  256. case shift > 0:
  257. // increased scale: decimal-shift dividend left
  258. ix = new(big.Int).Mul(x.Unscaled(), exp10(shift))
  259. iy = y.Unscaled()
  260. case shift < 0:
  261. // decreased scale: decimal-shift divisor left
  262. ix = x.Unscaled()
  263. iy = new(big.Int).Mul(y.Unscaled(), exp10(-shift))
  264. default:
  265. ix = x.Unscaled()
  266. iy = y.Unscaled()
  267. }
  268. // save a copy of iy in case it to be overwritten with the result
  269. iy2 := iy
  270. if iy == z.Unscaled() {
  271. iy2 = new(big.Int).Set(iy)
  272. }
  273. // set scale
  274. z.SetScale(s)
  275. // set unscaled
  276. if useRem {
  277. // Int division
  278. _, intr := z.Unscaled().QuoRem(ix, iy, new(big.Int))
  279. // set remainder
  280. remNum.Set(intr)
  281. remDen.Set(iy2)
  282. } else {
  283. z.Unscaled().Quo(ix, iy)
  284. }
  285. return z, remNum, remDen
  286. }
  287. // ScaleQuoExact is the Scaler used by QuoExact. It returns a scale that is
  288. // greater than or equal to "x.Scale() - y.Scale()"; it is calculated so that
  289. // the remainder will be zero whenever x/y is a finite decimal.
  290. var ScaleQuoExact Scaler = scaleQuoExact{}
  291. type scaleQuoExact struct{}
  292. func (sqe scaleQuoExact) Scale(x, y *Dec) Scale {
  293. rem := new(big.Rat).SetFrac(x.Unscaled(), y.Unscaled())
  294. f2, f5 := factor2(rem.Denom()), factor(rem.Denom(), bigInt[5])
  295. var f10 Scale
  296. if f2 > f5 {
  297. f10 = Scale(f2)
  298. } else {
  299. f10 = Scale(f5)
  300. }
  301. return x.Scale() - y.Scale() + f10
  302. }
  303. func factor(n *big.Int, p *big.Int) int {
  304. // could be improved for large factors
  305. d, f := n, 0
  306. for {
  307. dd, dm := new(big.Int).DivMod(d, p, new(big.Int))
  308. if dm.Sign() == 0 {
  309. f++
  310. d = dd
  311. } else {
  312. break
  313. }
  314. }
  315. return f
  316. }
  317. func factor2(n *big.Int) int {
  318. // could be improved for large factors
  319. f := 0
  320. for ; n.Bit(f) == 0; f++ {
  321. }
  322. return f
  323. }
  324. func upscale(a, b *Dec) (*Dec, *Dec) {
  325. if a.Scale() == b.Scale() {
  326. return a, b
  327. }
  328. if a.Scale() > b.Scale() {
  329. bb := b.rescale(a.Scale())
  330. return a, bb
  331. }
  332. aa := a.rescale(b.Scale())
  333. return aa, b
  334. }
  335. func exp10(x Scale) *big.Int {
  336. if int(x) < len(exp10cache) {
  337. return &exp10cache[int(x)]
  338. }
  339. return new(big.Int).Exp(bigInt[10], big.NewInt(int64(x)), nil)
  340. }
  341. func (x *Dec) rescale(newScale Scale) *Dec {
  342. shift := newScale - x.Scale()
  343. switch {
  344. case shift < 0:
  345. e := exp10(-shift)
  346. return NewDec(new(big.Int).Quo(x.Unscaled(), e), newScale)
  347. case shift > 0:
  348. e := exp10(shift)
  349. return NewDec(new(big.Int).Mul(x.Unscaled(), e), newScale)
  350. }
  351. return x
  352. }
  353. var zeros = []byte("00000000000000000000000000000000" +
  354. "00000000000000000000000000000000")
  355. var lzeros = Scale(len(zeros))
  356. func appendZeros(s []byte, n Scale) []byte {
  357. for i := Scale(0); i < n; i += lzeros {
  358. if n > i+lzeros {
  359. s = append(s, zeros...)
  360. } else {
  361. s = append(s, zeros[0:n-i]...)
  362. }
  363. }
  364. return s
  365. }
  366. func (x *Dec) String() string {
  367. if x == nil {
  368. return "<nil>"
  369. }
  370. scale := x.Scale()
  371. s := []byte(x.Unscaled().String())
  372. if scale <= 0 {
  373. if scale != 0 && x.unscaled.Sign() != 0 {
  374. s = appendZeros(s, -scale)
  375. }
  376. return string(s)
  377. }
  378. negbit := Scale(-((x.Sign() - 1) / 2))
  379. // scale > 0
  380. lens := Scale(len(s))
  381. if lens-negbit <= scale {
  382. ss := make([]byte, 0, scale+2)
  383. if negbit == 1 {
  384. ss = append(ss, '-')
  385. }
  386. ss = append(ss, '0', '.')
  387. ss = appendZeros(ss, scale-lens+negbit)
  388. ss = append(ss, s[negbit:]...)
  389. return string(ss)
  390. }
  391. // lens > scale
  392. ss := make([]byte, 0, lens+1)
  393. ss = append(ss, s[:lens-scale]...)
  394. ss = append(ss, '.')
  395. ss = append(ss, s[lens-scale:]...)
  396. return string(ss)
  397. }
  398. // Format is a support routine for fmt.Formatter. It accepts the decimal
  399. // formats 'd' and 'f', and handles both equivalently.
  400. // Width, precision, flags and bases 2, 8, 16 are not supported.
  401. func (x *Dec) Format(s fmt.State, ch rune) {
  402. if ch != 'd' && ch != 'f' && ch != 'v' && ch != 's' {
  403. fmt.Fprintf(s, "%%!%c(dec.Dec=%s)", ch, x.String())
  404. return
  405. }
  406. fmt.Fprintf(s, x.String())
  407. }
  408. func (z *Dec) scan(r io.RuneScanner) (*Dec, error) {
  409. unscaled := make([]byte, 0, 256) // collects chars of unscaled as bytes
  410. dp, dg := -1, -1 // indexes of decimal point, first digit
  411. loop:
  412. for {
  413. ch, _, err := r.ReadRune()
  414. if err == io.EOF {
  415. break loop
  416. }
  417. if err != nil {
  418. return nil, err
  419. }
  420. switch {
  421. case ch == '+' || ch == '-':
  422. if len(unscaled) > 0 || dp >= 0 { // must be first character
  423. r.UnreadRune()
  424. break loop
  425. }
  426. case ch == '.':
  427. if dp >= 0 {
  428. r.UnreadRune()
  429. break loop
  430. }
  431. dp = len(unscaled)
  432. continue // don't add to unscaled
  433. case ch >= '0' && ch <= '9':
  434. if dg == -1 {
  435. dg = len(unscaled)
  436. }
  437. default:
  438. r.UnreadRune()
  439. break loop
  440. }
  441. unscaled = append(unscaled, byte(ch))
  442. }
  443. if dg == -1 {
  444. return nil, fmt.Errorf("no digits read")
  445. }
  446. if dp >= 0 {
  447. z.SetScale(Scale(len(unscaled) - dp))
  448. } else {
  449. z.SetScale(0)
  450. }
  451. _, ok := z.Unscaled().SetString(string(unscaled), 10)
  452. if !ok {
  453. return nil, fmt.Errorf("invalid decimal: %s", string(unscaled))
  454. }
  455. return z, nil
  456. }
  457. // SetString sets z to the value of s, interpreted as a decimal (base 10),
  458. // and returns z and a boolean indicating success. The scale of z is the
  459. // number of digits after the decimal point (including any trailing 0s),
  460. // or 0 if there is no decimal point. If SetString fails, the value of z
  461. // is undefined but the returned value is nil.
  462. func (z *Dec) SetString(s string) (*Dec, bool) {
  463. r := strings.NewReader(s)
  464. _, err := z.scan(r)
  465. if err != nil {
  466. return nil, false
  467. }
  468. _, _, err = r.ReadRune()
  469. if err != io.EOF {
  470. return nil, false
  471. }
  472. // err == io.EOF => scan consumed all of s
  473. return z, true
  474. }
  475. // Scan is a support routine for fmt.Scanner; it sets z to the value of
  476. // the scanned number. It accepts the decimal formats 'd' and 'f', and
  477. // handles both equivalently. Bases 2, 8, 16 are not supported.
  478. // The scale of z is the number of digits after the decimal point
  479. // (including any trailing 0s), or 0 if there is no decimal point.
  480. func (z *Dec) Scan(s fmt.ScanState, ch rune) error {
  481. if ch != 'd' && ch != 'f' && ch != 's' && ch != 'v' {
  482. return fmt.Errorf("Dec.Scan: invalid verb '%c'", ch)
  483. }
  484. s.SkipSpace()
  485. _, err := z.scan(s)
  486. return err
  487. }
  488. // Gob encoding version
  489. const decGobVersion byte = 1
  490. func scaleBytes(s Scale) []byte {
  491. buf := make([]byte, scaleSize)
  492. i := scaleSize
  493. for j := 0; j < scaleSize; j++ {
  494. i--
  495. buf[i] = byte(s)
  496. s >>= 8
  497. }
  498. return buf
  499. }
  500. func scale(b []byte) (s Scale) {
  501. for j := 0; j < scaleSize; j++ {
  502. s <<= 8
  503. s |= Scale(b[j])
  504. }
  505. return
  506. }
  507. // GobEncode implements the gob.GobEncoder interface.
  508. func (x *Dec) GobEncode() ([]byte, error) {
  509. buf, err := x.Unscaled().GobEncode()
  510. if err != nil {
  511. return nil, err
  512. }
  513. buf = append(append(buf, scaleBytes(x.Scale())...), decGobVersion)
  514. return buf, nil
  515. }
  516. // GobDecode implements the gob.GobDecoder interface.
  517. func (z *Dec) GobDecode(buf []byte) error {
  518. if len(buf) == 0 {
  519. return fmt.Errorf("Dec.GobDecode: no data")
  520. }
  521. b := buf[len(buf)-1]
  522. if b != decGobVersion {
  523. return fmt.Errorf("Dec.GobDecode: encoding version %d not supported", b)
  524. }
  525. l := len(buf) - scaleSize - 1
  526. err := z.Unscaled().GobDecode(buf[:l])
  527. if err != nil {
  528. return err
  529. }
  530. z.SetScale(scale(buf[l : l+scaleSize]))
  531. return nil
  532. }