extfloat.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  1. // Copyright 2011 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. package fastprinter
  5. // An extFloat represents an extended floating-point number, with more
  6. // precision than a float64. It does not try to save bits: the
  7. // number represented by the structure is mant*(2^exp), with a negative
  8. // sign if neg is true.
  9. type extFloat struct {
  10. mant uint64
  11. exp int
  12. neg bool
  13. }
  14. // Powers of ten taken from double-conversion library.
  15. // http://code.google.com/p/double-conversion/
  16. const (
  17. firstPowerOfTen = -348
  18. stepPowerOfTen = 8
  19. )
  20. var smallPowersOfTen = [...]extFloat{
  21. {1 << 63, -63, false}, // 1
  22. {0xa << 60, -60, false}, // 1e1
  23. {0x64 << 57, -57, false}, // 1e2
  24. {0x3e8 << 54, -54, false}, // 1e3
  25. {0x2710 << 50, -50, false}, // 1e4
  26. {0x186a0 << 47, -47, false}, // 1e5
  27. {0xf4240 << 44, -44, false}, // 1e6
  28. {0x989680 << 40, -40, false}, // 1e7
  29. }
  30. var powersOfTen = [...]extFloat{
  31. {0xfa8fd5a0081c0288, -1220, false}, // 10^-348
  32. {0xbaaee17fa23ebf76, -1193, false}, // 10^-340
  33. {0x8b16fb203055ac76, -1166, false}, // 10^-332
  34. {0xcf42894a5dce35ea, -1140, false}, // 10^-324
  35. {0x9a6bb0aa55653b2d, -1113, false}, // 10^-316
  36. {0xe61acf033d1a45df, -1087, false}, // 10^-308
  37. {0xab70fe17c79ac6ca, -1060, false}, // 10^-300
  38. {0xff77b1fcbebcdc4f, -1034, false}, // 10^-292
  39. {0xbe5691ef416bd60c, -1007, false}, // 10^-284
  40. {0x8dd01fad907ffc3c, -980, false}, // 10^-276
  41. {0xd3515c2831559a83, -954, false}, // 10^-268
  42. {0x9d71ac8fada6c9b5, -927, false}, // 10^-260
  43. {0xea9c227723ee8bcb, -901, false}, // 10^-252
  44. {0xaecc49914078536d, -874, false}, // 10^-244
  45. {0x823c12795db6ce57, -847, false}, // 10^-236
  46. {0xc21094364dfb5637, -821, false}, // 10^-228
  47. {0x9096ea6f3848984f, -794, false}, // 10^-220
  48. {0xd77485cb25823ac7, -768, false}, // 10^-212
  49. {0xa086cfcd97bf97f4, -741, false}, // 10^-204
  50. {0xef340a98172aace5, -715, false}, // 10^-196
  51. {0xb23867fb2a35b28e, -688, false}, // 10^-188
  52. {0x84c8d4dfd2c63f3b, -661, false}, // 10^-180
  53. {0xc5dd44271ad3cdba, -635, false}, // 10^-172
  54. {0x936b9fcebb25c996, -608, false}, // 10^-164
  55. {0xdbac6c247d62a584, -582, false}, // 10^-156
  56. {0xa3ab66580d5fdaf6, -555, false}, // 10^-148
  57. {0xf3e2f893dec3f126, -529, false}, // 10^-140
  58. {0xb5b5ada8aaff80b8, -502, false}, // 10^-132
  59. {0x87625f056c7c4a8b, -475, false}, // 10^-124
  60. {0xc9bcff6034c13053, -449, false}, // 10^-116
  61. {0x964e858c91ba2655, -422, false}, // 10^-108
  62. {0xdff9772470297ebd, -396, false}, // 10^-100
  63. {0xa6dfbd9fb8e5b88f, -369, false}, // 10^-92
  64. {0xf8a95fcf88747d94, -343, false}, // 10^-84
  65. {0xb94470938fa89bcf, -316, false}, // 10^-76
  66. {0x8a08f0f8bf0f156b, -289, false}, // 10^-68
  67. {0xcdb02555653131b6, -263, false}, // 10^-60
  68. {0x993fe2c6d07b7fac, -236, false}, // 10^-52
  69. {0xe45c10c42a2b3b06, -210, false}, // 10^-44
  70. {0xaa242499697392d3, -183, false}, // 10^-36
  71. {0xfd87b5f28300ca0e, -157, false}, // 10^-28
  72. {0xbce5086492111aeb, -130, false}, // 10^-20
  73. {0x8cbccc096f5088cc, -103, false}, // 10^-12
  74. {0xd1b71758e219652c, -77, false}, // 10^-4
  75. {0x9c40000000000000, -50, false}, // 10^4
  76. {0xe8d4a51000000000, -24, false}, // 10^12
  77. {0xad78ebc5ac620000, 3, false}, // 10^20
  78. {0x813f3978f8940984, 30, false}, // 10^28
  79. {0xc097ce7bc90715b3, 56, false}, // 10^36
  80. {0x8f7e32ce7bea5c70, 83, false}, // 10^44
  81. {0xd5d238a4abe98068, 109, false}, // 10^52
  82. {0x9f4f2726179a2245, 136, false}, // 10^60
  83. {0xed63a231d4c4fb27, 162, false}, // 10^68
  84. {0xb0de65388cc8ada8, 189, false}, // 10^76
  85. {0x83c7088e1aab65db, 216, false}, // 10^84
  86. {0xc45d1df942711d9a, 242, false}, // 10^92
  87. {0x924d692ca61be758, 269, false}, // 10^100
  88. {0xda01ee641a708dea, 295, false}, // 10^108
  89. {0xa26da3999aef774a, 322, false}, // 10^116
  90. {0xf209787bb47d6b85, 348, false}, // 10^124
  91. {0xb454e4a179dd1877, 375, false}, // 10^132
  92. {0x865b86925b9bc5c2, 402, false}, // 10^140
  93. {0xc83553c5c8965d3d, 428, false}, // 10^148
  94. {0x952ab45cfa97a0b3, 455, false}, // 10^156
  95. {0xde469fbd99a05fe3, 481, false}, // 10^164
  96. {0xa59bc234db398c25, 508, false}, // 10^172
  97. {0xf6c69a72a3989f5c, 534, false}, // 10^180
  98. {0xb7dcbf5354e9bece, 561, false}, // 10^188
  99. {0x88fcf317f22241e2, 588, false}, // 10^196
  100. {0xcc20ce9bd35c78a5, 614, false}, // 10^204
  101. {0x98165af37b2153df, 641, false}, // 10^212
  102. {0xe2a0b5dc971f303a, 667, false}, // 10^220
  103. {0xa8d9d1535ce3b396, 694, false}, // 10^228
  104. {0xfb9b7cd9a4a7443c, 720, false}, // 10^236
  105. {0xbb764c4ca7a44410, 747, false}, // 10^244
  106. {0x8bab8eefb6409c1a, 774, false}, // 10^252
  107. {0xd01fef10a657842c, 800, false}, // 10^260
  108. {0x9b10a4e5e9913129, 827, false}, // 10^268
  109. {0xe7109bfba19c0c9d, 853, false}, // 10^276
  110. {0xac2820d9623bf429, 880, false}, // 10^284
  111. {0x80444b5e7aa7cf85, 907, false}, // 10^292
  112. {0xbf21e44003acdd2d, 933, false}, // 10^300
  113. {0x8e679c2f5e44ff8f, 960, false}, // 10^308
  114. {0xd433179d9c8cb841, 986, false}, // 10^316
  115. {0x9e19db92b4e31ba9, 1013, false}, // 10^324
  116. {0xeb96bf6ebadf77d9, 1039, false}, // 10^332
  117. {0xaf87023b9bf0ee6b, 1066, false}, // 10^340
  118. }
  119. // floatBits returns the bits of the float64 that best approximates
  120. // the extFloat passed as receiver. Overflow is set to true if
  121. // the resulting float64 is ±Inf.
  122. func (f *extFloat) floatBits(flt *floatInfo) (bits uint64, overflow bool) {
  123. f.Normalize()
  124. exp := f.exp + 63
  125. // Exponent too small.
  126. if exp < flt.bias+1 {
  127. n := flt.bias + 1 - exp
  128. f.mant >>= uint(n)
  129. exp += n
  130. }
  131. // Extract 1+flt.mantbits bits from the 64-bit mantissa.
  132. mant := f.mant >> (63 - flt.mantbits)
  133. if f.mant&(1<<(62-flt.mantbits)) != 0 {
  134. // Round up.
  135. mant += 1
  136. }
  137. // Rounding might have added a bit; shift down.
  138. if mant == 2<<flt.mantbits {
  139. mant >>= 1
  140. exp++
  141. }
  142. // Infinities.
  143. if exp-flt.bias >= 1<<flt.expbits-1 {
  144. // ±Inf
  145. mant = 0
  146. exp = 1<<flt.expbits - 1 + flt.bias
  147. overflow = true
  148. } else if mant&(1<<flt.mantbits) == 0 {
  149. // Denormalized?
  150. exp = flt.bias
  151. }
  152. // Assemble bits.
  153. bits = mant & (uint64(1)<<flt.mantbits - 1)
  154. bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits
  155. if f.neg {
  156. bits |= 1 << (flt.mantbits + flt.expbits)
  157. }
  158. return
  159. }
  160. // AssignComputeBounds sets f to the floating point value
  161. // defined by mant, exp and precision given by flt. It returns
  162. // lower, upper such that any number in the closed interval
  163. // [lower, upper] is converted back to the same floating point number.
  164. func (f *extFloat) AssignComputeBounds(mant uint64, exp int, neg bool, flt *floatInfo) (lower, upper extFloat) {
  165. f.mant = mant
  166. f.exp = exp - int(flt.mantbits)
  167. f.neg = neg
  168. if f.exp <= 0 && mant == (mant>>uint(-f.exp))<<uint(-f.exp) {
  169. // An exact integer
  170. f.mant >>= uint(-f.exp)
  171. f.exp = 0
  172. return *f, *f
  173. }
  174. expBiased := exp - flt.bias
  175. upper = extFloat{mant: 2*f.mant + 1, exp: f.exp - 1, neg: f.neg}
  176. if mant != 1<<flt.mantbits || expBiased == 1 {
  177. lower = extFloat{mant: 2*f.mant - 1, exp: f.exp - 1, neg: f.neg}
  178. } else {
  179. lower = extFloat{mant: 4*f.mant - 1, exp: f.exp - 2, neg: f.neg}
  180. }
  181. return
  182. }
  183. // Normalize normalizes f so that the highest bit of the mantissa is
  184. // set, and returns the number by which the mantissa was left-shifted.
  185. func (f *extFloat) Normalize() (shift uint) {
  186. mant, exp := f.mant, f.exp
  187. if mant == 0 {
  188. return 0
  189. }
  190. if mant>>(64-32) == 0 {
  191. mant <<= 32
  192. exp -= 32
  193. }
  194. if mant>>(64-16) == 0 {
  195. mant <<= 16
  196. exp -= 16
  197. }
  198. if mant>>(64-8) == 0 {
  199. mant <<= 8
  200. exp -= 8
  201. }
  202. if mant>>(64-4) == 0 {
  203. mant <<= 4
  204. exp -= 4
  205. }
  206. if mant>>(64-2) == 0 {
  207. mant <<= 2
  208. exp -= 2
  209. }
  210. if mant>>(64-1) == 0 {
  211. mant <<= 1
  212. exp -= 1
  213. }
  214. shift = uint(f.exp - exp)
  215. f.mant, f.exp = mant, exp
  216. return
  217. }
  218. // Multiply sets f to the product f*g: the result is correctly rounded,
  219. // but not normalized.
  220. func (f *extFloat) Multiply(g extFloat) {
  221. fhi, flo := f.mant>>32, uint64(uint32(f.mant))
  222. ghi, glo := g.mant>>32, uint64(uint32(g.mant))
  223. // Cross products.
  224. cross1 := fhi * glo
  225. cross2 := flo * ghi
  226. // f.mant*g.mant is fhi*ghi << 64 + (cross1+cross2) << 32 + flo*glo
  227. f.mant = fhi*ghi + (cross1 >> 32) + (cross2 >> 32)
  228. rem := uint64(uint32(cross1)) + uint64(uint32(cross2)) + ((flo * glo) >> 32)
  229. // Round up.
  230. rem += (1 << 31)
  231. f.mant += (rem >> 32)
  232. f.exp = f.exp + g.exp + 64
  233. }
  234. var uint64pow10 = [...]uint64{
  235. 1, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  236. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  237. }
  238. // AssignDecimal sets f to an approximate value mantissa*10^exp. It
  239. // reports whether the value represented by f is guaranteed to be the
  240. // best approximation of d after being rounded to a float64 or
  241. // float32 depending on flt.
  242. func (f *extFloat) AssignDecimal(mantissa uint64, exp10 int, neg bool, trunc bool, flt *floatInfo) (ok bool) {
  243. const uint64digits = 19
  244. const errorscale = 8
  245. errors := 0 // An upper bound for error, computed in errorscale*ulp.
  246. if trunc {
  247. // the decimal number was truncated.
  248. errors += errorscale / 2
  249. }
  250. f.mant = mantissa
  251. f.exp = 0
  252. f.neg = neg
  253. // Multiply by powers of ten.
  254. i := (exp10 - firstPowerOfTen) / stepPowerOfTen
  255. if exp10 < firstPowerOfTen || i >= len(powersOfTen) {
  256. return false
  257. }
  258. adjExp := (exp10 - firstPowerOfTen) % stepPowerOfTen
  259. // We multiply by exp%step
  260. if adjExp < uint64digits && mantissa < uint64pow10[uint64digits-adjExp] {
  261. // We can multiply the mantissa exactly.
  262. f.mant *= uint64pow10[adjExp]
  263. f.Normalize()
  264. } else {
  265. f.Normalize()
  266. f.Multiply(smallPowersOfTen[adjExp])
  267. errors += errorscale / 2
  268. }
  269. // We multiply by 10 to the exp - exp%step.
  270. f.Multiply(powersOfTen[i])
  271. if errors > 0 {
  272. errors += 1
  273. }
  274. errors += errorscale / 2
  275. // Normalize
  276. shift := f.Normalize()
  277. errors <<= shift
  278. // Now f is a good approximation of the decimal.
  279. // Check whether the error is too large: that is, if the mantissa
  280. // is perturbated by the error, the resulting float64 will change.
  281. // The 64 bits mantissa is 1 + 52 bits for float64 + 11 extra bits.
  282. //
  283. // In many cases the approximation will be good enough.
  284. denormalExp := flt.bias - 63
  285. var extrabits uint
  286. if f.exp <= denormalExp {
  287. // f.mant * 2^f.exp is smaller than 2^(flt.bias+1).
  288. extrabits = uint(63 - flt.mantbits + 1 + uint(denormalExp-f.exp))
  289. } else {
  290. extrabits = uint(63 - flt.mantbits)
  291. }
  292. halfway := uint64(1) << (extrabits - 1)
  293. mant_extra := f.mant & (1<<extrabits - 1)
  294. // Do a signed comparison here! If the error estimate could make
  295. // the mantissa round differently for the conversion to double,
  296. // then we can't give a definite answer.
  297. if int64(halfway)-int64(errors) < int64(mant_extra) &&
  298. int64(mant_extra) < int64(halfway)+int64(errors) {
  299. return false
  300. }
  301. return true
  302. }
  303. // Frexp10 is an analogue of math.Frexp for decimal powers. It scales
  304. // f by an approximate power of ten 10^-exp, and returns exp10, so
  305. // that f*10^exp10 has the same value as the old f, up to an ulp,
  306. // as well as the index of 10^-exp in the powersOfTen table.
  307. func (f *extFloat) frexp10() (exp10, index int) {
  308. // The constants expMin and expMax constrain the final value of the
  309. // binary exponent of f. We want a small integral part in the result
  310. // because finding digits of an integer requires divisions, whereas
  311. // digits of the fractional part can be found by repeatedly multiplying
  312. // by 10.
  313. const expMin = -60
  314. const expMax = -32
  315. // Find power of ten such that x * 10^n has a binary exponent
  316. // between expMin and expMax.
  317. approxExp10 := ((expMin+expMax)/2 - f.exp) * 28 / 93 // log(10)/log(2) is close to 93/28.
  318. i := (approxExp10 - firstPowerOfTen) / stepPowerOfTen
  319. Loop:
  320. for {
  321. exp := f.exp + powersOfTen[i].exp + 64
  322. switch {
  323. case exp < expMin:
  324. i++
  325. case exp > expMax:
  326. i--
  327. default:
  328. break Loop
  329. }
  330. }
  331. // Apply the desired decimal shift on f. It will have exponent
  332. // in the desired range. This is multiplication by 10^-exp10.
  333. f.Multiply(powersOfTen[i])
  334. return -(firstPowerOfTen + i*stepPowerOfTen), i
  335. }
  336. // frexp10Many applies a common shift by a power of ten to a, b, c.
  337. func frexp10Many(a, b, c *extFloat) (exp10 int) {
  338. exp10, i := c.frexp10()
  339. a.Multiply(powersOfTen[i])
  340. b.Multiply(powersOfTen[i])
  341. return
  342. }
  343. // FixedDecimal stores in d the first n significant digits
  344. // of the decimal representation of f. It returns false
  345. // if it cannot be sure of the answer.
  346. func (f *extFloat) FixedDecimal(d *decimalSlice, n int) bool {
  347. if f.mant == 0 {
  348. d.nd = 0
  349. d.dp = 0
  350. d.neg = f.neg
  351. return true
  352. }
  353. if n == 0 {
  354. panic("strconv: internal error: extFloat.FixedDecimal called with n == 0")
  355. }
  356. // Multiply by an appropriate power of ten to have a reasonable
  357. // number to process.
  358. f.Normalize()
  359. exp10, _ := f.frexp10()
  360. shift := uint(-f.exp)
  361. integer := uint32(f.mant >> shift)
  362. fraction := f.mant - (uint64(integer) << shift)
  363. ε := uint64(1) // ε is the uncertainty we have on the mantissa of f.
  364. // Write exactly n digits to d.
  365. needed := n // how many digits are left to write.
  366. integerDigits := 0 // the number of decimal digits of integer.
  367. pow10 := uint64(1) // the power of ten by which f was scaled.
  368. for i, pow := 0, uint64(1); i < 20; i++ {
  369. if pow > uint64(integer) {
  370. integerDigits = i
  371. break
  372. }
  373. pow *= 10
  374. }
  375. rest := integer
  376. if integerDigits > needed {
  377. // the integral part is already large, trim the last digits.
  378. pow10 = uint64pow10[integerDigits-needed]
  379. integer /= uint32(pow10)
  380. rest -= integer * uint32(pow10)
  381. } else {
  382. rest = 0
  383. }
  384. // Write the digits of integer: the digits of rest are omitted.
  385. var buf [32]byte
  386. pos := len(buf)
  387. for v := integer; v > 0; {
  388. v1 := v / 10
  389. v -= 10 * v1
  390. pos--
  391. buf[pos] = byte(v + '0')
  392. v = v1
  393. }
  394. for i := pos; i < len(buf); i++ {
  395. d.d[i-pos] = buf[i]
  396. }
  397. nd := len(buf) - pos
  398. d.nd = nd
  399. d.dp = integerDigits + exp10
  400. needed -= nd
  401. if needed > 0 {
  402. if rest != 0 || pow10 != 1 {
  403. panic("strconv: internal error, rest != 0 but needed > 0")
  404. }
  405. // Emit digits for the fractional part. Each time, 10*fraction
  406. // fits in a uint64 without overflow.
  407. for needed > 0 {
  408. fraction *= 10
  409. ε *= 10 // the uncertainty scales as we multiply by ten.
  410. if 2*ε > 1<<shift {
  411. // the error is so large it could modify which digit to write, abort.
  412. return false
  413. }
  414. digit := fraction >> shift
  415. d.d[nd] = byte(digit + '0')
  416. fraction -= digit << shift
  417. nd++
  418. needed--
  419. }
  420. d.nd = nd
  421. }
  422. // We have written a truncation of f (a numerator / 10^d.dp). The remaining part
  423. // can be interpreted as a small number (< 1) to be added to the last digit of the
  424. // numerator.
  425. //
  426. // If rest > 0, the amount is:
  427. // (rest<<shift | fraction) / (pow10 << shift)
  428. // fraction being known with a ±ε uncertainty.
  429. // The fact that n > 0 guarantees that pow10 << shift does not overflow a uint64.
  430. //
  431. // If rest = 0, pow10 == 1 and the amount is
  432. // fraction / (1 << shift)
  433. // fraction being known with a ±ε uncertainty.
  434. //
  435. // We pass this information to the rounding routine for adjustment.
  436. ok := adjustLastDigitFixed(d, uint64(rest)<<shift|fraction, pow10, shift, ε)
  437. if !ok {
  438. return false
  439. }
  440. // Trim trailing zeros.
  441. for i := d.nd - 1; i >= 0; i-- {
  442. if d.d[i] != '0' {
  443. d.nd = i + 1
  444. break
  445. }
  446. }
  447. return true
  448. }
  449. // adjustLastDigitFixed assumes d contains the representation of the integral part
  450. // of some number, whose fractional part is num / (den << shift). The numerator
  451. // num is only known up to an uncertainty of size ε, assumed to be less than
  452. // (den << shift)/2.
  453. //
  454. // It will increase the last digit by one to account for correct rounding, typically
  455. // when the fractional part is greater than 1/2, and will return false if ε is such
  456. // that no correct answer can be given.
  457. func adjustLastDigitFixed(d *decimalSlice, num, den uint64, shift uint, ε uint64) bool {
  458. if num > den<<shift {
  459. panic("strconv: num > den<<shift in adjustLastDigitFixed")
  460. }
  461. if 2*ε > den<<shift {
  462. panic("strconv: ε > (den<<shift)/2")
  463. }
  464. if 2*(num+ε) < den<<shift {
  465. return true
  466. }
  467. if 2*(num-ε) > den<<shift {
  468. // increment d by 1.
  469. i := d.nd - 1
  470. for ; i >= 0; i-- {
  471. if d.d[i] == '9' {
  472. d.nd--
  473. } else {
  474. break
  475. }
  476. }
  477. if i < 0 {
  478. d.d[0] = '1'
  479. d.nd = 1
  480. d.dp++
  481. } else {
  482. d.d[i]++
  483. }
  484. return true
  485. }
  486. return false
  487. }
  488. // ShortestDecimal stores in d the shortest decimal representation of f
  489. // which belongs to the open interval (lower, upper), where f is supposed
  490. // to lie. It returns false whenever the result is unsure. The implementation
  491. // uses the Grisu3 algorithm.
  492. func (f *extFloat) ShortestDecimal(d *decimalSlice, lower, upper *extFloat) bool {
  493. if f.mant == 0 {
  494. d.nd = 0
  495. d.dp = 0
  496. d.neg = f.neg
  497. return true
  498. }
  499. if f.exp == 0 && *lower == *f && *lower == *upper {
  500. // an exact integer.
  501. var buf [24]byte
  502. n := len(buf) - 1
  503. for v := f.mant; v > 0; {
  504. v1 := v / 10
  505. v -= 10 * v1
  506. buf[n] = byte(v + '0')
  507. n--
  508. v = v1
  509. }
  510. nd := len(buf) - n - 1
  511. for i := 0; i < nd; i++ {
  512. d.d[i] = buf[n+1+i]
  513. }
  514. d.nd, d.dp = nd, nd
  515. for d.nd > 0 && d.d[d.nd-1] == '0' {
  516. d.nd--
  517. }
  518. if d.nd == 0 {
  519. d.dp = 0
  520. }
  521. d.neg = f.neg
  522. return true
  523. }
  524. upper.Normalize()
  525. // Uniformize exponents.
  526. if f.exp > upper.exp {
  527. f.mant <<= uint(f.exp - upper.exp)
  528. f.exp = upper.exp
  529. }
  530. if lower.exp > upper.exp {
  531. lower.mant <<= uint(lower.exp - upper.exp)
  532. lower.exp = upper.exp
  533. }
  534. exp10 := frexp10Many(lower, f, upper)
  535. // Take a safety margin due to rounding in frexp10Many, but we lose precision.
  536. upper.mant++
  537. lower.mant--
  538. // The shortest representation of f is either rounded up or down, but
  539. // in any case, it is a truncation of upper.
  540. shift := uint(-upper.exp)
  541. integer := uint32(upper.mant >> shift)
  542. fraction := upper.mant - (uint64(integer) << shift)
  543. // How far we can go down from upper until the result is wrong.
  544. allowance := upper.mant - lower.mant
  545. // How far we should go to get a very precise result.
  546. targetDiff := upper.mant - f.mant
  547. // Count integral digits: there are at most 10.
  548. var integerDigits int
  549. for i, pow := 0, uint64(1); i < 20; i++ {
  550. if pow > uint64(integer) {
  551. integerDigits = i
  552. break
  553. }
  554. pow *= 10
  555. }
  556. for i := 0; i < integerDigits; i++ {
  557. pow := uint64pow10[integerDigits-i-1]
  558. digit := integer / uint32(pow)
  559. d.d[i] = byte(digit + '0')
  560. integer -= digit * uint32(pow)
  561. // evaluate whether we should stop.
  562. if currentDiff := uint64(integer)<<shift + fraction; currentDiff < allowance {
  563. d.nd = i + 1
  564. d.dp = integerDigits + exp10
  565. d.neg = f.neg
  566. // Sometimes allowance is so large the last digit might need to be
  567. // decremented to get closer to f.
  568. return adjustLastDigit(d, currentDiff, targetDiff, allowance, pow<<shift, 2)
  569. }
  570. }
  571. d.nd = integerDigits
  572. d.dp = d.nd + exp10
  573. d.neg = f.neg
  574. // Compute digits of the fractional part. At each step fraction does not
  575. // overflow. The choice of minExp implies that fraction is less than 2^60.
  576. var digit int
  577. multiplier := uint64(1)
  578. for {
  579. fraction *= 10
  580. multiplier *= 10
  581. digit = int(fraction >> shift)
  582. d.d[d.nd] = byte(digit + '0')
  583. d.nd++
  584. fraction -= uint64(digit) << shift
  585. if fraction < allowance*multiplier {
  586. // We are in the admissible range. Note that if allowance is about to
  587. // overflow, that is, allowance > 2^64/10, the condition is automatically
  588. // true due to the limited range of fraction.
  589. return adjustLastDigit(d,
  590. fraction, targetDiff*multiplier, allowance*multiplier,
  591. 1<<shift, multiplier*2)
  592. }
  593. }
  594. }
  595. // adjustLastDigit modifies d = x-currentDiff*ε, to get closest to
  596. // d = x-targetDiff*ε, without becoming smaller than x-maxDiff*ε.
  597. // It assumes that a decimal digit is worth ulpDecimal*ε, and that
  598. // all data is known with a error estimate of ulpBinary*ε.
  599. func adjustLastDigit(d *decimalSlice, currentDiff, targetDiff, maxDiff, ulpDecimal, ulpBinary uint64) bool {
  600. if ulpDecimal < 2*ulpBinary {
  601. // Approximation is too wide.
  602. return false
  603. }
  604. for currentDiff+ulpDecimal/2+ulpBinary < targetDiff {
  605. d.d[d.nd-1]--
  606. currentDiff += ulpDecimal
  607. }
  608. if currentDiff+ulpDecimal <= targetDiff+ulpDecimal/2+ulpBinary {
  609. // we have two choices, and don't know what to do.
  610. return false
  611. }
  612. if currentDiff < ulpBinary || currentDiff > maxDiff-ulpBinary {
  613. // we went too far
  614. return false
  615. }
  616. if d.nd == 1 && d.d[0] == '0' {
  617. // the number has actually reached zero.
  618. d.nd = 0
  619. d.dp = 0
  620. }
  621. return true
  622. }