dtoa.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. package fast
  2. import (
  3. "fmt"
  4. "strconv"
  5. )
  6. const (
  7. kMinimalTargetExponent = -60
  8. kMaximalTargetExponent = -32
  9. kTen4 = 10000
  10. kTen5 = 100000
  11. kTen6 = 1000000
  12. kTen7 = 10000000
  13. kTen8 = 100000000
  14. kTen9 = 1000000000
  15. )
  16. type Mode int
  17. const (
  18. ModeShortest Mode = iota
  19. ModePrecision
  20. )
  21. // Adjusts the last digit of the generated number, and screens out generated
  22. // solutions that may be inaccurate. A solution may be inaccurate if it is
  23. // outside the safe interval, or if we cannot prove that it is closer to the
  24. // input than a neighboring representation of the same length.
  25. //
  26. // Input: * buffer containing the digits of too_high / 10^kappa
  27. // - distance_too_high_w == (too_high - w).f() * unit
  28. // - unsafe_interval == (too_high - too_low).f() * unit
  29. // - rest = (too_high - buffer * 10^kappa).f() * unit
  30. // - ten_kappa = 10^kappa * unit
  31. // - unit = the common multiplier
  32. //
  33. // Output: returns true if the buffer is guaranteed to contain the closest
  34. //
  35. // representable number to the input.
  36. // Modifies the generated digits in the buffer to approach (round towards) w.
  37. func roundWeed(buffer []byte, distance_too_high_w, unsafe_interval, rest, ten_kappa, unit uint64) bool {
  38. small_distance := distance_too_high_w - unit
  39. big_distance := distance_too_high_w + unit
  40. // Let w_low = too_high - big_distance, and
  41. // w_high = too_high - small_distance.
  42. // Note: w_low < w < w_high
  43. //
  44. // The real w (* unit) must lie somewhere inside the interval
  45. // ]w_low; w_high[ (often written as "(w_low; w_high)")
  46. // Basically the buffer currently contains a number in the unsafe interval
  47. // ]too_low; too_high[ with too_low < w < too_high
  48. //
  49. // too_high - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  50. // ^v 1 unit ^ ^ ^ ^
  51. // boundary_high --------------------- . . . .
  52. // ^v 1 unit . . . .
  53. // - - - - - - - - - - - - - - - - - - - + - - + - - - - - - . .
  54. // . . ^ . .
  55. // . big_distance . . .
  56. // . . . . rest
  57. // small_distance . . . .
  58. // v . . . .
  59. // w_high - - - - - - - - - - - - - - - - - - . . . .
  60. // ^v 1 unit . . . .
  61. // w ---------------------------------------- . . . .
  62. // ^v 1 unit v . . .
  63. // w_low - - - - - - - - - - - - - - - - - - - - - . . .
  64. // . . v
  65. // buffer --------------------------------------------------+-------+--------
  66. // . .
  67. // safe_interval .
  68. // v .
  69. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - .
  70. // ^v 1 unit .
  71. // boundary_low ------------------------- unsafe_interval
  72. // ^v 1 unit v
  73. // too_low - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  74. //
  75. //
  76. // Note that the value of buffer could lie anywhere inside the range too_low
  77. // to too_high.
  78. //
  79. // boundary_low, boundary_high and w are approximations of the real boundaries
  80. // and v (the input number). They are guaranteed to be precise up to one unit.
  81. // In fact the error is guaranteed to be strictly less than one unit.
  82. //
  83. // Anything that lies outside the unsafe interval is guaranteed not to round
  84. // to v when read again.
  85. // Anything that lies inside the safe interval is guaranteed to round to v
  86. // when read again.
  87. // If the number inside the buffer lies inside the unsafe interval but not
  88. // inside the safe interval then we simply do not know and bail out (returning
  89. // false).
  90. //
  91. // Similarly we have to take into account the imprecision of 'w' when finding
  92. // the closest representation of 'w'. If we have two potential
  93. // representations, and one is closer to both w_low and w_high, then we know
  94. // it is closer to the actual value v.
  95. //
  96. // By generating the digits of too_high we got the largest (closest to
  97. // too_high) buffer that is still in the unsafe interval. In the case where
  98. // w_high < buffer < too_high we try to decrement the buffer.
  99. // This way the buffer approaches (rounds towards) w.
  100. // There are 3 conditions that stop the decrementation process:
  101. // 1) the buffer is already below w_high
  102. // 2) decrementing the buffer would make it leave the unsafe interval
  103. // 3) decrementing the buffer would yield a number below w_high and farther
  104. // away than the current number. In other words:
  105. // (buffer{-1} < w_high) && w_high - buffer{-1} > buffer - w_high
  106. // Instead of using the buffer directly we use its distance to too_high.
  107. // Conceptually rest ~= too_high - buffer
  108. // We need to do the following tests in this order to avoid over- and
  109. // underflows.
  110. _DCHECK(rest <= unsafe_interval)
  111. for rest < small_distance && // Negated condition 1
  112. unsafe_interval-rest >= ten_kappa && // Negated condition 2
  113. (rest+ten_kappa < small_distance || // buffer{-1} > w_high
  114. small_distance-rest >= rest+ten_kappa-small_distance) {
  115. buffer[len(buffer)-1]--
  116. rest += ten_kappa
  117. }
  118. // We have approached w+ as much as possible. We now test if approaching w-
  119. // would require changing the buffer. If yes, then we have two possible
  120. // representations close to w, but we cannot decide which one is closer.
  121. if rest < big_distance && unsafe_interval-rest >= ten_kappa &&
  122. (rest+ten_kappa < big_distance ||
  123. big_distance-rest > rest+ten_kappa-big_distance) {
  124. return false
  125. }
  126. // Weeding test.
  127. // The safe interval is [too_low + 2 ulp; too_high - 2 ulp]
  128. // Since too_low = too_high - unsafe_interval this is equivalent to
  129. // [too_high - unsafe_interval + 4 ulp; too_high - 2 ulp]
  130. // Conceptually we have: rest ~= too_high - buffer
  131. return (2*unit <= rest) && (rest <= unsafe_interval-4*unit)
  132. }
  133. // Rounds the buffer upwards if the result is closer to v by possibly adding
  134. // 1 to the buffer. If the precision of the calculation is not sufficient to
  135. // round correctly, return false.
  136. // The rounding might shift the whole buffer in which case the kappa is
  137. // adjusted. For example "99", kappa = 3 might become "10", kappa = 4.
  138. //
  139. // If 2*rest > ten_kappa then the buffer needs to be round up.
  140. // rest can have an error of +/- 1 unit. This function accounts for the
  141. // imprecision and returns false, if the rounding direction cannot be
  142. // unambiguously determined.
  143. //
  144. // Precondition: rest < ten_kappa.
  145. func roundWeedCounted(buffer []byte, rest, ten_kappa, unit uint64, kappa *int) bool {
  146. _DCHECK(rest < ten_kappa)
  147. // The following tests are done in a specific order to avoid overflows. They
  148. // will work correctly with any uint64 values of rest < ten_kappa and unit.
  149. //
  150. // If the unit is too big, then we don't know which way to round. For example
  151. // a unit of 50 means that the real number lies within rest +/- 50. If
  152. // 10^kappa == 40 then there is no way to tell which way to round.
  153. if unit >= ten_kappa {
  154. return false
  155. }
  156. // Even if unit is just half the size of 10^kappa we are already completely
  157. // lost. (And after the previous test we know that the expression will not
  158. // over/underflow.)
  159. if ten_kappa-unit <= unit {
  160. return false
  161. }
  162. // If 2 * (rest + unit) <= 10^kappa we can safely round down.
  163. if (ten_kappa-rest > rest) && (ten_kappa-2*rest >= 2*unit) {
  164. return true
  165. }
  166. // If 2 * (rest - unit) >= 10^kappa, then we can safely round up.
  167. if (rest > unit) && (ten_kappa-(rest-unit) <= (rest - unit)) {
  168. // Increment the last digit recursively until we find a non '9' digit.
  169. buffer[len(buffer)-1]++
  170. for i := len(buffer) - 1; i > 0; i-- {
  171. if buffer[i] != '0'+10 {
  172. break
  173. }
  174. buffer[i] = '0'
  175. buffer[i-1]++
  176. }
  177. // If the first digit is now '0'+ 10 we had a buffer with all '9's. With the
  178. // exception of the first digit all digits are now '0'. Simply switch the
  179. // first digit to '1' and adjust the kappa. Example: "99" becomes "10" and
  180. // the power (the kappa) is increased.
  181. if buffer[0] == '0'+10 {
  182. buffer[0] = '1'
  183. *kappa += 1
  184. }
  185. return true
  186. }
  187. return false
  188. }
  189. // Returns the biggest power of ten that is less than or equal than the given
  190. // number. We furthermore receive the maximum number of bits 'number' has.
  191. // If number_bits == 0 then 0^-1 is returned
  192. // The number of bits must be <= 32.
  193. // Precondition: number < (1 << (number_bits + 1)).
  194. func biggestPowerTen(number uint32, number_bits int) (power uint32, exponent int) {
  195. switch number_bits {
  196. case 32, 31, 30:
  197. if kTen9 <= number {
  198. power = kTen9
  199. exponent = 9
  200. break
  201. }
  202. fallthrough
  203. case 29, 28, 27:
  204. if kTen8 <= number {
  205. power = kTen8
  206. exponent = 8
  207. break
  208. }
  209. fallthrough
  210. case 26, 25, 24:
  211. if kTen7 <= number {
  212. power = kTen7
  213. exponent = 7
  214. break
  215. }
  216. fallthrough
  217. case 23, 22, 21, 20:
  218. if kTen6 <= number {
  219. power = kTen6
  220. exponent = 6
  221. break
  222. }
  223. fallthrough
  224. case 19, 18, 17:
  225. if kTen5 <= number {
  226. power = kTen5
  227. exponent = 5
  228. break
  229. }
  230. fallthrough
  231. case 16, 15, 14:
  232. if kTen4 <= number {
  233. power = kTen4
  234. exponent = 4
  235. break
  236. }
  237. fallthrough
  238. case 13, 12, 11, 10:
  239. if 1000 <= number {
  240. power = 1000
  241. exponent = 3
  242. break
  243. }
  244. fallthrough
  245. case 9, 8, 7:
  246. if 100 <= number {
  247. power = 100
  248. exponent = 2
  249. break
  250. }
  251. fallthrough
  252. case 6, 5, 4:
  253. if 10 <= number {
  254. power = 10
  255. exponent = 1
  256. break
  257. }
  258. fallthrough
  259. case 3, 2, 1:
  260. if 1 <= number {
  261. power = 1
  262. exponent = 0
  263. break
  264. }
  265. fallthrough
  266. case 0:
  267. power = 0
  268. exponent = -1
  269. }
  270. return
  271. }
  272. // Generates the digits of input number w.
  273. // w is a floating-point number (DiyFp), consisting of a significand and an
  274. // exponent. Its exponent is bounded by kMinimalTargetExponent and
  275. // kMaximalTargetExponent.
  276. //
  277. // Hence -60 <= w.e() <= -32.
  278. //
  279. // Returns false if it fails, in which case the generated digits in the buffer
  280. // should not be used.
  281. // Preconditions:
  282. // - low, w and high are correct up to 1 ulp (unit in the last place). That
  283. // is, their error must be less than a unit of their last digits.
  284. // - low.e() == w.e() == high.e()
  285. // - low < w < high, and taking into account their error: low~ <= high~
  286. // - kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
  287. //
  288. // Postconditions: returns false if procedure fails.
  289. //
  290. // otherwise:
  291. // * buffer is not null-terminated, but len contains the number of digits.
  292. // * buffer contains the shortest possible decimal digit-sequence
  293. // such that LOW < buffer * 10^kappa < HIGH, where LOW and HIGH are the
  294. // correct values of low and high (without their error).
  295. // * if more than one decimal representation gives the minimal number of
  296. // decimal digits then the one closest to W (where W is the correct value
  297. // of w) is chosen.
  298. //
  299. // Remark: this procedure takes into account the imprecision of its input
  300. //
  301. // numbers. If the precision is not enough to guarantee all the postconditions
  302. // then false is returned. This usually happens rarely (~0.5%).
  303. //
  304. // Say, for the sake of example, that
  305. //
  306. // w.e() == -48, and w.f() == 0x1234567890ABCDEF
  307. //
  308. // w's value can be computed by w.f() * 2^w.e()
  309. // We can obtain w's integral digits by simply shifting w.f() by -w.e().
  310. //
  311. // -> w's integral part is 0x1234
  312. // w's fractional part is therefore 0x567890ABCDEF.
  313. //
  314. // Printing w's integral part is easy (simply print 0x1234 in decimal).
  315. // In order to print its fraction we repeatedly multiply the fraction by 10 and
  316. // get each digit. Example the first digit after the point would be computed by
  317. //
  318. // (0x567890ABCDEF * 10) >> 48. -> 3
  319. //
  320. // The whole thing becomes slightly more complicated because we want to stop
  321. // once we have enough digits. That is, once the digits inside the buffer
  322. // represent 'w' we can stop. Everything inside the interval low - high
  323. // represents w. However we have to pay attention to low, high and w's
  324. // imprecision.
  325. func digitGen(low, w, high diyfp, buffer []byte) (kappa int, buf []byte, res bool) {
  326. _DCHECK(low.e == w.e && w.e == high.e)
  327. _DCHECK(low.f+1 <= high.f-1)
  328. _DCHECK(kMinimalTargetExponent <= w.e && w.e <= kMaximalTargetExponent)
  329. // low, w and high are imprecise, but by less than one ulp (unit in the last
  330. // place).
  331. // If we remove (resp. add) 1 ulp from low (resp. high) we are certain that
  332. // the new numbers are outside of the interval we want the final
  333. // representation to lie in.
  334. // Inversely adding (resp. removing) 1 ulp from low (resp. high) would yield
  335. // numbers that are certain to lie in the interval. We will use this fact
  336. // later on.
  337. // We will now start by generating the digits within the uncertain
  338. // interval. Later we will weed out representations that lie outside the safe
  339. // interval and thus _might_ lie outside the correct interval.
  340. unit := uint64(1)
  341. too_low := diyfp{f: low.f - unit, e: low.e}
  342. too_high := diyfp{f: high.f + unit, e: high.e}
  343. // too_low and too_high are guaranteed to lie outside the interval we want the
  344. // generated number in.
  345. unsafe_interval := too_high.minus(too_low)
  346. // We now cut the input number into two parts: the integral digits and the
  347. // fractionals. We will not write any decimal separator though, but adapt
  348. // kappa instead.
  349. // Reminder: we are currently computing the digits (stored inside the buffer)
  350. // such that: too_low < buffer * 10^kappa < too_high
  351. // We use too_high for the digit_generation and stop as soon as possible.
  352. // If we stop early we effectively round down.
  353. one := diyfp{f: 1 << -w.e, e: w.e}
  354. // Division by one is a shift.
  355. integrals := uint32(too_high.f >> -one.e)
  356. // Modulo by one is an and.
  357. fractionals := too_high.f & (one.f - 1)
  358. divisor, divisor_exponent := biggestPowerTen(integrals, diyFpKSignificandSize-(-one.e))
  359. kappa = divisor_exponent + 1
  360. buf = buffer
  361. for kappa > 0 {
  362. digit := int(integrals / divisor)
  363. buf = append(buf, byte('0'+digit))
  364. integrals %= divisor
  365. kappa--
  366. // Note that kappa now equals the exponent of the divisor and that the
  367. // invariant thus holds again.
  368. rest := uint64(integrals)<<-one.e + fractionals
  369. // Invariant: too_high = buffer * 10^kappa + DiyFp(rest, one.e)
  370. // Reminder: unsafe_interval.e == one.e
  371. if rest < unsafe_interval.f {
  372. // Rounding down (by not emitting the remaining digits) yields a number
  373. // that lies within the unsafe interval.
  374. res = roundWeed(buf, too_high.minus(w).f,
  375. unsafe_interval.f, rest,
  376. uint64(divisor)<<-one.e, unit)
  377. return
  378. }
  379. divisor /= 10
  380. }
  381. // The integrals have been generated. We are at the point of the decimal
  382. // separator. In the following loop we simply multiply the remaining digits by
  383. // 10 and divide by one. We just need to pay attention to multiply associated
  384. // data (like the interval or 'unit'), too.
  385. // Note that the multiplication by 10 does not overflow, because w.e >= -60
  386. // and thus one.e >= -60.
  387. _DCHECK(one.e >= -60)
  388. _DCHECK(fractionals < one.f)
  389. _DCHECK(0xFFFFFFFFFFFFFFFF/10 >= one.f)
  390. for {
  391. fractionals *= 10
  392. unit *= 10
  393. unsafe_interval.f *= 10
  394. // Integer division by one.
  395. digit := byte(fractionals >> -one.e)
  396. buf = append(buf, '0'+digit)
  397. fractionals &= one.f - 1 // Modulo by one.
  398. kappa--
  399. if fractionals < unsafe_interval.f {
  400. res = roundWeed(buf, too_high.minus(w).f*unit, unsafe_interval.f, fractionals, one.f, unit)
  401. return
  402. }
  403. }
  404. }
  405. // Generates (at most) requested_digits of input number w.
  406. // w is a floating-point number (DiyFp), consisting of a significand and an
  407. // exponent. Its exponent is bounded by kMinimalTargetExponent and
  408. // kMaximalTargetExponent.
  409. //
  410. // Hence -60 <= w.e() <= -32.
  411. //
  412. // Returns false if it fails, in which case the generated digits in the buffer
  413. // should not be used.
  414. // Preconditions:
  415. // - w is correct up to 1 ulp (unit in the last place). That
  416. // is, its error must be strictly less than a unit of its last digit.
  417. // - kMinimalTargetExponent <= w.e() <= kMaximalTargetExponent
  418. //
  419. // Postconditions: returns false if procedure fails.
  420. //
  421. // otherwise:
  422. // * buffer is not null-terminated, but length contains the number of
  423. // digits.
  424. // * the representation in buffer is the most precise representation of
  425. // requested_digits digits.
  426. // * buffer contains at most requested_digits digits of w. If there are less
  427. // than requested_digits digits then some trailing '0's have been removed.
  428. // * kappa is such that
  429. // w = buffer * 10^kappa + eps with |eps| < 10^kappa / 2.
  430. //
  431. // Remark: This procedure takes into account the imprecision of its input
  432. //
  433. // numbers. If the precision is not enough to guarantee all the postconditions
  434. // then false is returned. This usually happens rarely, but the failure-rate
  435. // increases with higher requested_digits.
  436. func digitGenCounted(w diyfp, requested_digits int, buffer []byte) (kappa int, buf []byte, res bool) {
  437. _DCHECK(kMinimalTargetExponent <= w.e && w.e <= kMaximalTargetExponent)
  438. // w is assumed to have an error less than 1 unit. Whenever w is scaled we
  439. // also scale its error.
  440. w_error := uint64(1)
  441. // We cut the input number into two parts: the integral digits and the
  442. // fractional digits. We don't emit any decimal separator, but adapt kappa
  443. // instead. Example: instead of writing "1.2" we put "12" into the buffer and
  444. // increase kappa by 1.
  445. one := diyfp{f: 1 << -w.e, e: w.e}
  446. // Division by one is a shift.
  447. integrals := uint32(w.f >> -one.e)
  448. // Modulo by one is an and.
  449. fractionals := w.f & (one.f - 1)
  450. divisor, divisor_exponent := biggestPowerTen(integrals, diyFpKSignificandSize-(-one.e))
  451. kappa = divisor_exponent + 1
  452. buf = buffer
  453. // Loop invariant: buffer = w / 10^kappa (integer division)
  454. // The invariant holds for the first iteration: kappa has been initialized
  455. // with the divisor exponent + 1. And the divisor is the biggest power of ten
  456. // that is smaller than 'integrals'.
  457. for kappa > 0 {
  458. digit := byte(integrals / divisor)
  459. buf = append(buf, '0'+digit)
  460. requested_digits--
  461. integrals %= divisor
  462. kappa--
  463. // Note that kappa now equals the exponent of the divisor and that the
  464. // invariant thus holds again.
  465. if requested_digits == 0 {
  466. break
  467. }
  468. divisor /= 10
  469. }
  470. if requested_digits == 0 {
  471. rest := uint64(integrals)<<-one.e + fractionals
  472. res = roundWeedCounted(buf, rest, uint64(divisor)<<-one.e, w_error, &kappa)
  473. return
  474. }
  475. // The integrals have been generated. We are at the point of the decimal
  476. // separator. In the following loop we simply multiply the remaining digits by
  477. // 10 and divide by one. We just need to pay attention to multiply associated
  478. // data (the 'unit'), too.
  479. // Note that the multiplication by 10 does not overflow, because w.e >= -60
  480. // and thus one.e >= -60.
  481. _DCHECK(one.e >= -60)
  482. _DCHECK(fractionals < one.f)
  483. _DCHECK(0xFFFFFFFFFFFFFFFF/10 >= one.f)
  484. for requested_digits > 0 && fractionals > w_error {
  485. fractionals *= 10
  486. w_error *= 10
  487. // Integer division by one.
  488. digit := byte(fractionals >> -one.e)
  489. buf = append(buf, '0'+digit)
  490. requested_digits--
  491. fractionals &= one.f - 1 // Modulo by one.
  492. kappa--
  493. }
  494. if requested_digits != 0 {
  495. res = false
  496. } else {
  497. res = roundWeedCounted(buf, fractionals, one.f, w_error, &kappa)
  498. }
  499. return
  500. }
  501. // Provides a decimal representation of v.
  502. // Returns true if it succeeds, otherwise the result cannot be trusted.
  503. // There will be *length digits inside the buffer (not null-terminated).
  504. // If the function returns true then
  505. //
  506. // v == (double) (buffer * 10^decimal_exponent).
  507. //
  508. // The digits in the buffer are the shortest representation possible: no
  509. // 0.09999999999999999 instead of 0.1. The shorter representation will even be
  510. // chosen even if the longer one would be closer to v.
  511. // The last digit will be closest to the actual v. That is, even if several
  512. // digits might correctly yield 'v' when read again, the closest will be
  513. // computed.
  514. func grisu3(f float64, buffer []byte) (digits []byte, decimal_exponent int, result bool) {
  515. v := double(f)
  516. w := v.toNormalizedDiyfp()
  517. // boundary_minus and boundary_plus are the boundaries between v and its
  518. // closest floating-point neighbors. Any number strictly between
  519. // boundary_minus and boundary_plus will round to v when convert to a double.
  520. // Grisu3 will never output representations that lie exactly on a boundary.
  521. boundary_minus, boundary_plus := v.normalizedBoundaries()
  522. ten_mk_minimal_binary_exponent := kMinimalTargetExponent - (w.e + diyFpKSignificandSize)
  523. ten_mk_maximal_binary_exponent := kMaximalTargetExponent - (w.e + diyFpKSignificandSize)
  524. ten_mk, mk := getCachedPowerForBinaryExponentRange(ten_mk_minimal_binary_exponent, ten_mk_maximal_binary_exponent)
  525. _DCHECK(
  526. (kMinimalTargetExponent <=
  527. w.e+ten_mk.e+diyFpKSignificandSize) &&
  528. (kMaximalTargetExponent >= w.e+ten_mk.e+diyFpKSignificandSize))
  529. // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
  530. // 64 bit significand and ten_mk is thus only precise up to 64 bits.
  531. // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
  532. // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
  533. // off by a small amount.
  534. // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
  535. // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
  536. // (f-1) * 2^e < w*10^k < (f+1) * 2^e
  537. scaled_w := w.times(ten_mk)
  538. _DCHECK(scaled_w.e ==
  539. boundary_plus.e+ten_mk.e+diyFpKSignificandSize)
  540. // In theory it would be possible to avoid some recomputations by computing
  541. // the difference between w and boundary_minus/plus (a power of 2) and to
  542. // compute scaled_boundary_minus/plus by subtracting/adding from
  543. // scaled_w. However the code becomes much less readable and the speed
  544. // enhancements are not terrific.
  545. scaled_boundary_minus := boundary_minus.times(ten_mk)
  546. scaled_boundary_plus := boundary_plus.times(ten_mk)
  547. // DigitGen will generate the digits of scaled_w. Therefore we have
  548. // v == (double) (scaled_w * 10^-mk).
  549. // Set decimal_exponent == -mk and pass it to DigitGen. If scaled_w is not an
  550. // integer than it will be updated. For instance if scaled_w == 1.23 then
  551. // the buffer will be filled with "123" und the decimal_exponent will be
  552. // decreased by 2.
  553. var kappa int
  554. kappa, digits, result = digitGen(scaled_boundary_minus, scaled_w, scaled_boundary_plus, buffer)
  555. decimal_exponent = -mk + kappa
  556. return
  557. }
  558. // The "counted" version of grisu3 (see above) only generates requested_digits
  559. // number of digits. This version does not generate the shortest representation,
  560. // and with enough requested digits 0.1 will at some point print as 0.9999999...
  561. // Grisu3 is too imprecise for real halfway cases (1.5 will not work) and
  562. // therefore the rounding strategy for halfway cases is irrelevant.
  563. func grisu3Counted(v float64, requested_digits int, buffer []byte) (digits []byte, decimal_exponent int, result bool) {
  564. w := double(v).toNormalizedDiyfp()
  565. ten_mk_minimal_binary_exponent := kMinimalTargetExponent - (w.e + diyFpKSignificandSize)
  566. ten_mk_maximal_binary_exponent := kMaximalTargetExponent - (w.e + diyFpKSignificandSize)
  567. ten_mk, mk := getCachedPowerForBinaryExponentRange(ten_mk_minimal_binary_exponent, ten_mk_maximal_binary_exponent)
  568. _DCHECK(
  569. (kMinimalTargetExponent <=
  570. w.e+ten_mk.e+diyFpKSignificandSize) &&
  571. (kMaximalTargetExponent >= w.e+ten_mk.e+diyFpKSignificandSize))
  572. // Note that ten_mk is only an approximation of 10^-k. A DiyFp only contains a
  573. // 64 bit significand and ten_mk is thus only precise up to 64 bits.
  574. // The DiyFp::Times procedure rounds its result, and ten_mk is approximated
  575. // too. The variable scaled_w (as well as scaled_boundary_minus/plus) are now
  576. // off by a small amount.
  577. // In fact: scaled_w - w*10^k < 1ulp (unit in the last place) of scaled_w.
  578. // In other words: let f = scaled_w.f() and e = scaled_w.e(), then
  579. // (f-1) * 2^e < w*10^k < (f+1) * 2^e
  580. scaled_w := w.times(ten_mk)
  581. // We now have (double) (scaled_w * 10^-mk).
  582. // DigitGen will generate the first requested_digits digits of scaled_w and
  583. // return together with a kappa such that scaled_w ~= buffer * 10^kappa. (It
  584. // will not always be exactly the same since DigitGenCounted only produces a
  585. // limited number of digits.)
  586. var kappa int
  587. kappa, digits, result = digitGenCounted(scaled_w, requested_digits, buffer)
  588. decimal_exponent = -mk + kappa
  589. return
  590. }
  591. // v must be > 0 and must not be Inf or NaN
  592. func Dtoa(v float64, mode Mode, requested_digits int, buffer []byte) (digits []byte, decimal_point int, result bool) {
  593. defer func() {
  594. if x := recover(); x != nil {
  595. if x == dcheckFailure {
  596. panic(fmt.Errorf("DCHECK assertion failed while formatting %s in mode %d", strconv.FormatFloat(v, 'e', 50, 64), mode))
  597. }
  598. panic(x)
  599. }
  600. }()
  601. var decimal_exponent int
  602. startPos := len(buffer)
  603. switch mode {
  604. case ModeShortest:
  605. digits, decimal_exponent, result = grisu3(v, buffer)
  606. case ModePrecision:
  607. digits, decimal_exponent, result = grisu3Counted(v, requested_digits, buffer)
  608. }
  609. if result {
  610. decimal_point = len(digits) - startPos + decimal_exponent
  611. } else {
  612. digits = digits[:startPos]
  613. }
  614. return
  615. }