decimal-go.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. // Copyright 2009 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Multiprecision decimal numbers.
  5. // For floating-point formatting only; not general purpose.
  6. // Only operations are assign and (binary) left/right shift.
  7. // Can do binary floating point in multiprecision decimal precisely
  8. // because 2 divides 10; cannot do decimal floating point
  9. // in multiprecision binary precisely.
  10. package decimal
  11. type decimal struct {
  12. d [800]byte // digits, big-endian representation
  13. nd int // number of digits used
  14. dp int // decimal point
  15. neg bool // negative flag
  16. trunc bool // discarded nonzero digits beyond d[:nd]
  17. }
  18. func (a *decimal) String() string {
  19. n := 10 + a.nd
  20. if a.dp > 0 {
  21. n += a.dp
  22. }
  23. if a.dp < 0 {
  24. n += -a.dp
  25. }
  26. buf := make([]byte, n)
  27. w := 0
  28. switch {
  29. case a.nd == 0:
  30. return "0"
  31. case a.dp <= 0:
  32. // zeros fill space between decimal point and digits
  33. buf[w] = '0'
  34. w++
  35. buf[w] = '.'
  36. w++
  37. w += digitZero(buf[w : w+-a.dp])
  38. w += copy(buf[w:], a.d[0:a.nd])
  39. case a.dp < a.nd:
  40. // decimal point in middle of digits
  41. w += copy(buf[w:], a.d[0:a.dp])
  42. buf[w] = '.'
  43. w++
  44. w += copy(buf[w:], a.d[a.dp:a.nd])
  45. default:
  46. // zeros fill space between digits and decimal point
  47. w += copy(buf[w:], a.d[0:a.nd])
  48. w += digitZero(buf[w : w+a.dp-a.nd])
  49. }
  50. return string(buf[0:w])
  51. }
  52. func digitZero(dst []byte) int {
  53. for i := range dst {
  54. dst[i] = '0'
  55. }
  56. return len(dst)
  57. }
  58. // trim trailing zeros from number.
  59. // (They are meaningless; the decimal point is tracked
  60. // independent of the number of digits.)
  61. func trim(a *decimal) {
  62. for a.nd > 0 && a.d[a.nd-1] == '0' {
  63. a.nd--
  64. }
  65. if a.nd == 0 {
  66. a.dp = 0
  67. }
  68. }
  69. // Assign v to a.
  70. func (a *decimal) Assign(v uint64) {
  71. var buf [24]byte
  72. // Write reversed decimal in buf.
  73. n := 0
  74. for v > 0 {
  75. v1 := v / 10
  76. v -= 10 * v1
  77. buf[n] = byte(v + '0')
  78. n++
  79. v = v1
  80. }
  81. // Reverse again to produce forward decimal in a.d.
  82. a.nd = 0
  83. for n--; n >= 0; n-- {
  84. a.d[a.nd] = buf[n]
  85. a.nd++
  86. }
  87. a.dp = a.nd
  88. trim(a)
  89. }
  90. // Maximum shift that we can do in one pass without overflow.
  91. // A uint has 32 or 64 bits, and we have to be able to accommodate 9<<k.
  92. const uintSize = 32 << (^uint(0) >> 63)
  93. const maxShift = uintSize - 4
  94. // Binary shift right (/ 2) by k bits. k <= maxShift to avoid overflow.
  95. func rightShift(a *decimal, k uint) {
  96. r := 0 // read pointer
  97. w := 0 // write pointer
  98. // Pick up enough leading digits to cover first shift.
  99. var n uint
  100. for ; n>>k == 0; r++ {
  101. if r >= a.nd {
  102. if n == 0 {
  103. // a == 0; shouldn't get here, but handle anyway.
  104. a.nd = 0
  105. return
  106. }
  107. for n>>k == 0 {
  108. n = n * 10
  109. r++
  110. }
  111. break
  112. }
  113. c := uint(a.d[r])
  114. n = n*10 + c - '0'
  115. }
  116. a.dp -= r - 1
  117. var mask uint = (1 << k) - 1
  118. // Pick up a digit, put down a digit.
  119. for ; r < a.nd; r++ {
  120. c := uint(a.d[r])
  121. dig := n >> k
  122. n &= mask
  123. a.d[w] = byte(dig + '0')
  124. w++
  125. n = n*10 + c - '0'
  126. }
  127. // Put down extra digits.
  128. for n > 0 {
  129. dig := n >> k
  130. n &= mask
  131. if w < len(a.d) {
  132. a.d[w] = byte(dig + '0')
  133. w++
  134. } else if dig > 0 {
  135. a.trunc = true
  136. }
  137. n = n * 10
  138. }
  139. a.nd = w
  140. trim(a)
  141. }
  142. // Cheat sheet for left shift: table indexed by shift count giving
  143. // number of new digits that will be introduced by that shift.
  144. //
  145. // For example, leftcheats[4] = {2, "625"}. That means that
  146. // if we are shifting by 4 (multiplying by 16), it will add 2 digits
  147. // when the string prefix is "625" through "999", and one fewer digit
  148. // if the string prefix is "000" through "624".
  149. //
  150. // Credit for this trick goes to Ken.
  151. type leftCheat struct {
  152. delta int // number of new digits
  153. cutoff string // minus one digit if original < a.
  154. }
  155. var leftcheats = []leftCheat{
  156. // Leading digits of 1/2^i = 5^i.
  157. // 5^23 is not an exact 64-bit floating point number,
  158. // so have to use bc for the math.
  159. // Go up to 60 to be large enough for 32bit and 64bit platforms.
  160. /*
  161. seq 60 | sed 's/^/5^/' | bc |
  162. awk 'BEGIN{ print "\t{ 0, \"\" }," }
  163. {
  164. log2 = log(2)/log(10)
  165. printf("\t{ %d, \"%s\" },\t// * %d\n",
  166. int(log2*NR+1), $0, 2**NR)
  167. }'
  168. */
  169. {0, ""},
  170. {1, "5"}, // * 2
  171. {1, "25"}, // * 4
  172. {1, "125"}, // * 8
  173. {2, "625"}, // * 16
  174. {2, "3125"}, // * 32
  175. {2, "15625"}, // * 64
  176. {3, "78125"}, // * 128
  177. {3, "390625"}, // * 256
  178. {3, "1953125"}, // * 512
  179. {4, "9765625"}, // * 1024
  180. {4, "48828125"}, // * 2048
  181. {4, "244140625"}, // * 4096
  182. {4, "1220703125"}, // * 8192
  183. {5, "6103515625"}, // * 16384
  184. {5, "30517578125"}, // * 32768
  185. {5, "152587890625"}, // * 65536
  186. {6, "762939453125"}, // * 131072
  187. {6, "3814697265625"}, // * 262144
  188. {6, "19073486328125"}, // * 524288
  189. {7, "95367431640625"}, // * 1048576
  190. {7, "476837158203125"}, // * 2097152
  191. {7, "2384185791015625"}, // * 4194304
  192. {7, "11920928955078125"}, // * 8388608
  193. {8, "59604644775390625"}, // * 16777216
  194. {8, "298023223876953125"}, // * 33554432
  195. {8, "1490116119384765625"}, // * 67108864
  196. {9, "7450580596923828125"}, // * 134217728
  197. {9, "37252902984619140625"}, // * 268435456
  198. {9, "186264514923095703125"}, // * 536870912
  199. {10, "931322574615478515625"}, // * 1073741824
  200. {10, "4656612873077392578125"}, // * 2147483648
  201. {10, "23283064365386962890625"}, // * 4294967296
  202. {10, "116415321826934814453125"}, // * 8589934592
  203. {11, "582076609134674072265625"}, // * 17179869184
  204. {11, "2910383045673370361328125"}, // * 34359738368
  205. {11, "14551915228366851806640625"}, // * 68719476736
  206. {12, "72759576141834259033203125"}, // * 137438953472
  207. {12, "363797880709171295166015625"}, // * 274877906944
  208. {12, "1818989403545856475830078125"}, // * 549755813888
  209. {13, "9094947017729282379150390625"}, // * 1099511627776
  210. {13, "45474735088646411895751953125"}, // * 2199023255552
  211. {13, "227373675443232059478759765625"}, // * 4398046511104
  212. {13, "1136868377216160297393798828125"}, // * 8796093022208
  213. {14, "5684341886080801486968994140625"}, // * 17592186044416
  214. {14, "28421709430404007434844970703125"}, // * 35184372088832
  215. {14, "142108547152020037174224853515625"}, // * 70368744177664
  216. {15, "710542735760100185871124267578125"}, // * 140737488355328
  217. {15, "3552713678800500929355621337890625"}, // * 281474976710656
  218. {15, "17763568394002504646778106689453125"}, // * 562949953421312
  219. {16, "88817841970012523233890533447265625"}, // * 1125899906842624
  220. {16, "444089209850062616169452667236328125"}, // * 2251799813685248
  221. {16, "2220446049250313080847263336181640625"}, // * 4503599627370496
  222. {16, "11102230246251565404236316680908203125"}, // * 9007199254740992
  223. {17, "55511151231257827021181583404541015625"}, // * 18014398509481984
  224. {17, "277555756156289135105907917022705078125"}, // * 36028797018963968
  225. {17, "1387778780781445675529539585113525390625"}, // * 72057594037927936
  226. {18, "6938893903907228377647697925567626953125"}, // * 144115188075855872
  227. {18, "34694469519536141888238489627838134765625"}, // * 288230376151711744
  228. {18, "173472347597680709441192448139190673828125"}, // * 576460752303423488
  229. {19, "867361737988403547205962240695953369140625"}, // * 1152921504606846976
  230. }
  231. // Is the leading prefix of b lexicographically less than s?
  232. func prefixIsLessThan(b []byte, s string) bool {
  233. for i := 0; i < len(s); i++ {
  234. if i >= len(b) {
  235. return true
  236. }
  237. if b[i] != s[i] {
  238. return b[i] < s[i]
  239. }
  240. }
  241. return false
  242. }
  243. // Binary shift left (* 2) by k bits. k <= maxShift to avoid overflow.
  244. func leftShift(a *decimal, k uint) {
  245. delta := leftcheats[k].delta
  246. if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
  247. delta--
  248. }
  249. r := a.nd // read index
  250. w := a.nd + delta // write index
  251. // Pick up a digit, put down a digit.
  252. var n uint
  253. for r--; r >= 0; r-- {
  254. n += (uint(a.d[r]) - '0') << k
  255. quo := n / 10
  256. rem := n - 10*quo
  257. w--
  258. if w < len(a.d) {
  259. a.d[w] = byte(rem + '0')
  260. } else if rem != 0 {
  261. a.trunc = true
  262. }
  263. n = quo
  264. }
  265. // Put down extra digits.
  266. for n > 0 {
  267. quo := n / 10
  268. rem := n - 10*quo
  269. w--
  270. if w < len(a.d) {
  271. a.d[w] = byte(rem + '0')
  272. } else if rem != 0 {
  273. a.trunc = true
  274. }
  275. n = quo
  276. }
  277. a.nd += delta
  278. if a.nd >= len(a.d) {
  279. a.nd = len(a.d)
  280. }
  281. a.dp += delta
  282. trim(a)
  283. }
  284. // Binary shift left (k > 0) or right (k < 0).
  285. func (a *decimal) Shift(k int) {
  286. switch {
  287. case a.nd == 0:
  288. // nothing to do: a == 0
  289. case k > 0:
  290. for k > maxShift {
  291. leftShift(a, maxShift)
  292. k -= maxShift
  293. }
  294. leftShift(a, uint(k))
  295. case k < 0:
  296. for k < -maxShift {
  297. rightShift(a, maxShift)
  298. k += maxShift
  299. }
  300. rightShift(a, uint(-k))
  301. }
  302. }
  303. // If we chop a at nd digits, should we round up?
  304. func shouldRoundUp(a *decimal, nd int) bool {
  305. if nd < 0 || nd >= a.nd {
  306. return false
  307. }
  308. if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
  309. // if we truncated, a little higher than what's recorded - always round up
  310. if a.trunc {
  311. return true
  312. }
  313. return nd > 0 && (a.d[nd-1]-'0')%2 != 0
  314. }
  315. // not halfway - digit tells all
  316. return a.d[nd] >= '5'
  317. }
  318. // Round a to nd digits (or fewer).
  319. // If nd is zero, it means we're rounding
  320. // just to the left of the digits, as in
  321. // 0.09 -> 0.1.
  322. func (a *decimal) Round(nd int) {
  323. if nd < 0 || nd >= a.nd {
  324. return
  325. }
  326. if shouldRoundUp(a, nd) {
  327. a.RoundUp(nd)
  328. } else {
  329. a.RoundDown(nd)
  330. }
  331. }
  332. // Round a down to nd digits (or fewer).
  333. func (a *decimal) RoundDown(nd int) {
  334. if nd < 0 || nd >= a.nd {
  335. return
  336. }
  337. a.nd = nd
  338. trim(a)
  339. }
  340. // Round a up to nd digits (or fewer).
  341. func (a *decimal) RoundUp(nd int) {
  342. if nd < 0 || nd >= a.nd {
  343. return
  344. }
  345. // round up
  346. for i := nd - 1; i >= 0; i-- {
  347. c := a.d[i]
  348. if c < '9' { // can stop after this digit
  349. a.d[i]++
  350. a.nd = i + 1
  351. return
  352. }
  353. }
  354. // Number is all 9s.
  355. // Change to single 1 with adjusted decimal point.
  356. a.d[0] = '1'
  357. a.nd = 1
  358. a.dp++
  359. }
  360. // Extract integer part, rounded appropriately.
  361. // No guarantees about overflow.
  362. func (a *decimal) RoundedInteger() uint64 {
  363. if a.dp > 20 {
  364. return 0xFFFFFFFFFFFFFFFF
  365. }
  366. var i int
  367. n := uint64(0)
  368. for i = 0; i < a.dp && i < a.nd; i++ {
  369. n = n*10 + uint64(a.d[i]-'0')
  370. }
  371. for ; i < a.dp; i++ {
  372. n *= 10
  373. }
  374. if shouldRoundUp(a, a.dp) {
  375. n++
  376. }
  377. return n
  378. }