atof.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /**
  2. * Copyright 2014 Paul Querna
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. /* Portions of this file are on Go stdlib's strconv/atof.go */
  18. // Copyright 2009 The Go Authors. All rights reserved.
  19. // Use of this source code is governed by a BSD-style
  20. // license that can be found in the LICENSE file.
  21. package internal
  22. // decimal to binary floating point conversion.
  23. // Algorithm:
  24. // 1) Store input in multiprecision decimal.
  25. // 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
  26. // 3) Multiply by 2^precision and round to get mantissa.
  27. import "math"
  28. var optimize = true // can change for testing
  29. func equalIgnoreCase(s1 []byte, s2 []byte) bool {
  30. if len(s1) != len(s2) {
  31. return false
  32. }
  33. for i := 0; i < len(s1); i++ {
  34. c1 := s1[i]
  35. if 'A' <= c1 && c1 <= 'Z' {
  36. c1 += 'a' - 'A'
  37. }
  38. c2 := s2[i]
  39. if 'A' <= c2 && c2 <= 'Z' {
  40. c2 += 'a' - 'A'
  41. }
  42. if c1 != c2 {
  43. return false
  44. }
  45. }
  46. return true
  47. }
  48. func special(s []byte) (f float64, ok bool) {
  49. if len(s) == 0 {
  50. return
  51. }
  52. switch s[0] {
  53. default:
  54. return
  55. case '+':
  56. if equalIgnoreCase(s, []byte("+inf")) || equalIgnoreCase(s, []byte("+infinity")) {
  57. return math.Inf(1), true
  58. }
  59. case '-':
  60. if equalIgnoreCase(s, []byte("-inf")) || equalIgnoreCase(s, []byte("-infinity")) {
  61. return math.Inf(-1), true
  62. }
  63. case 'n', 'N':
  64. if equalIgnoreCase(s, []byte("nan")) {
  65. return math.NaN(), true
  66. }
  67. case 'i', 'I':
  68. if equalIgnoreCase(s, []byte("inf")) || equalIgnoreCase(s, []byte("infinity")) {
  69. return math.Inf(1), true
  70. }
  71. }
  72. return
  73. }
  74. func (b *decimal) set(s []byte) (ok bool) {
  75. i := 0
  76. b.neg = false
  77. b.trunc = false
  78. // optional sign
  79. if i >= len(s) {
  80. return
  81. }
  82. switch {
  83. case s[i] == '+':
  84. i++
  85. case s[i] == '-':
  86. b.neg = true
  87. i++
  88. }
  89. // digits
  90. sawdot := false
  91. sawdigits := false
  92. for ; i < len(s); i++ {
  93. switch {
  94. case s[i] == '.':
  95. if sawdot {
  96. return
  97. }
  98. sawdot = true
  99. b.dp = b.nd
  100. continue
  101. case '0' <= s[i] && s[i] <= '9':
  102. sawdigits = true
  103. if s[i] == '0' && b.nd == 0 { // ignore leading zeros
  104. b.dp--
  105. continue
  106. }
  107. if b.nd < len(b.d) {
  108. b.d[b.nd] = s[i]
  109. b.nd++
  110. } else if s[i] != '0' {
  111. b.trunc = true
  112. }
  113. continue
  114. }
  115. break
  116. }
  117. if !sawdigits {
  118. return
  119. }
  120. if !sawdot {
  121. b.dp = b.nd
  122. }
  123. // optional exponent moves decimal point.
  124. // if we read a very large, very long number,
  125. // just be sure to move the decimal point by
  126. // a lot (say, 100000). it doesn't matter if it's
  127. // not the exact number.
  128. if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
  129. i++
  130. if i >= len(s) {
  131. return
  132. }
  133. esign := 1
  134. if s[i] == '+' {
  135. i++
  136. } else if s[i] == '-' {
  137. i++
  138. esign = -1
  139. }
  140. if i >= len(s) || s[i] < '0' || s[i] > '9' {
  141. return
  142. }
  143. e := 0
  144. for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
  145. if e < 10000 {
  146. e = e*10 + int(s[i]) - '0'
  147. }
  148. }
  149. b.dp += e * esign
  150. }
  151. if i != len(s) {
  152. return
  153. }
  154. ok = true
  155. return
  156. }
  157. // readFloat reads a decimal mantissa and exponent from a float
  158. // string representation. It sets ok to false if the number could
  159. // not fit return types or is invalid.
  160. func readFloat(s []byte) (mantissa uint64, exp int, neg, trunc, ok bool) {
  161. const uint64digits = 19
  162. i := 0
  163. // optional sign
  164. if i >= len(s) {
  165. return
  166. }
  167. switch {
  168. case s[i] == '+':
  169. i++
  170. case s[i] == '-':
  171. neg = true
  172. i++
  173. }
  174. // digits
  175. sawdot := false
  176. sawdigits := false
  177. nd := 0
  178. ndMant := 0
  179. dp := 0
  180. for ; i < len(s); i++ {
  181. switch c := s[i]; true {
  182. case c == '.':
  183. if sawdot {
  184. return
  185. }
  186. sawdot = true
  187. dp = nd
  188. continue
  189. case '0' <= c && c <= '9':
  190. sawdigits = true
  191. if c == '0' && nd == 0 { // ignore leading zeros
  192. dp--
  193. continue
  194. }
  195. nd++
  196. if ndMant < uint64digits {
  197. mantissa *= 10
  198. mantissa += uint64(c - '0')
  199. ndMant++
  200. } else if s[i] != '0' {
  201. trunc = true
  202. }
  203. continue
  204. }
  205. break
  206. }
  207. if !sawdigits {
  208. return
  209. }
  210. if !sawdot {
  211. dp = nd
  212. }
  213. // optional exponent moves decimal point.
  214. // if we read a very large, very long number,
  215. // just be sure to move the decimal point by
  216. // a lot (say, 100000). it doesn't matter if it's
  217. // not the exact number.
  218. if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
  219. i++
  220. if i >= len(s) {
  221. return
  222. }
  223. esign := 1
  224. if s[i] == '+' {
  225. i++
  226. } else if s[i] == '-' {
  227. i++
  228. esign = -1
  229. }
  230. if i >= len(s) || s[i] < '0' || s[i] > '9' {
  231. return
  232. }
  233. e := 0
  234. for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
  235. if e < 10000 {
  236. e = e*10 + int(s[i]) - '0'
  237. }
  238. }
  239. dp += e * esign
  240. }
  241. if i != len(s) {
  242. return
  243. }
  244. exp = dp - ndMant
  245. ok = true
  246. return
  247. }
  248. // decimal power of ten to binary power of two.
  249. var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
  250. func (d *decimal) floatBits(flt *floatInfo) (b uint64, overflow bool) {
  251. var exp int
  252. var mant uint64
  253. // Zero is always a special case.
  254. if d.nd == 0 {
  255. mant = 0
  256. exp = flt.bias
  257. goto out
  258. }
  259. // Obvious overflow/underflow.
  260. // These bounds are for 64-bit floats.
  261. // Will have to change if we want to support 80-bit floats in the future.
  262. if d.dp > 310 {
  263. goto overflow
  264. }
  265. if d.dp < -330 {
  266. // zero
  267. mant = 0
  268. exp = flt.bias
  269. goto out
  270. }
  271. // Scale by powers of two until in range [0.5, 1.0)
  272. exp = 0
  273. for d.dp > 0 {
  274. var n int
  275. if d.dp >= len(powtab) {
  276. n = 27
  277. } else {
  278. n = powtab[d.dp]
  279. }
  280. d.Shift(-n)
  281. exp += n
  282. }
  283. for d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
  284. var n int
  285. if -d.dp >= len(powtab) {
  286. n = 27
  287. } else {
  288. n = powtab[-d.dp]
  289. }
  290. d.Shift(n)
  291. exp -= n
  292. }
  293. // Our range is [0.5,1) but floating point range is [1,2).
  294. exp--
  295. // Minimum representable exponent is flt.bias+1.
  296. // If the exponent is smaller, move it up and
  297. // adjust d accordingly.
  298. if exp < flt.bias+1 {
  299. n := flt.bias + 1 - exp
  300. d.Shift(-n)
  301. exp += n
  302. }
  303. if exp-flt.bias >= 1<<flt.expbits-1 {
  304. goto overflow
  305. }
  306. // Extract 1+flt.mantbits bits.
  307. d.Shift(int(1 + flt.mantbits))
  308. mant = d.RoundedInteger()
  309. // Rounding might have added a bit; shift down.
  310. if mant == 2<<flt.mantbits {
  311. mant >>= 1
  312. exp++
  313. if exp-flt.bias >= 1<<flt.expbits-1 {
  314. goto overflow
  315. }
  316. }
  317. // Denormalized?
  318. if mant&(1<<flt.mantbits) == 0 {
  319. exp = flt.bias
  320. }
  321. goto out
  322. overflow:
  323. // ±Inf
  324. mant = 0
  325. exp = 1<<flt.expbits - 1 + flt.bias
  326. overflow = true
  327. out:
  328. // Assemble bits.
  329. bits := mant & (uint64(1)<<flt.mantbits - 1)
  330. bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits
  331. if d.neg {
  332. bits |= 1 << flt.mantbits << flt.expbits
  333. }
  334. return bits, overflow
  335. }
  336. // Exact powers of 10.
  337. var float64pow10 = []float64{
  338. 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
  339. 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
  340. 1e20, 1e21, 1e22,
  341. }
  342. var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
  343. // If possible to convert decimal representation to 64-bit float f exactly,
  344. // entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
  345. // Three common cases:
  346. // value is exact integer
  347. // value is exact integer * exact power of ten
  348. // value is exact integer / exact power of ten
  349. // These all produce potentially inexact but correctly rounded answers.
  350. func atof64exact(mantissa uint64, exp int, neg bool) (f float64, ok bool) {
  351. if mantissa>>float64info.mantbits != 0 {
  352. return
  353. }
  354. f = float64(mantissa)
  355. if neg {
  356. f = -f
  357. }
  358. switch {
  359. case exp == 0:
  360. // an integer.
  361. return f, true
  362. // Exact integers are <= 10^15.
  363. // Exact powers of ten are <= 10^22.
  364. case exp > 0 && exp <= 15+22: // int * 10^k
  365. // If exponent is big but number of digits is not,
  366. // can move a few zeros into the integer part.
  367. if exp > 22 {
  368. f *= float64pow10[exp-22]
  369. exp = 22
  370. }
  371. if f > 1e15 || f < -1e15 {
  372. // the exponent was really too large.
  373. return
  374. }
  375. return f * float64pow10[exp], true
  376. case exp < 0 && exp >= -22: // int / 10^k
  377. return f / float64pow10[-exp], true
  378. }
  379. return
  380. }
  381. // If possible to compute mantissa*10^exp to 32-bit float f exactly,
  382. // entirely in floating-point math, do so, avoiding the machinery above.
  383. func atof32exact(mantissa uint64, exp int, neg bool) (f float32, ok bool) {
  384. if mantissa>>float32info.mantbits != 0 {
  385. return
  386. }
  387. f = float32(mantissa)
  388. if neg {
  389. f = -f
  390. }
  391. switch {
  392. case exp == 0:
  393. return f, true
  394. // Exact integers are <= 10^7.
  395. // Exact powers of ten are <= 10^10.
  396. case exp > 0 && exp <= 7+10: // int * 10^k
  397. // If exponent is big but number of digits is not,
  398. // can move a few zeros into the integer part.
  399. if exp > 10 {
  400. f *= float32pow10[exp-10]
  401. exp = 10
  402. }
  403. if f > 1e7 || f < -1e7 {
  404. // the exponent was really too large.
  405. return
  406. }
  407. return f * float32pow10[exp], true
  408. case exp < 0 && exp >= -10: // int / 10^k
  409. return f / float32pow10[-exp], true
  410. }
  411. return
  412. }
  413. const fnParseFloat = "ParseFloat"
  414. func atof32(s []byte) (f float32, err error) {
  415. if val, ok := special(s); ok {
  416. return float32(val), nil
  417. }
  418. if optimize {
  419. // Parse mantissa and exponent.
  420. mantissa, exp, neg, trunc, ok := readFloat(s)
  421. if ok {
  422. // Try pure floating-point arithmetic conversion.
  423. if !trunc {
  424. if f, ok := atof32exact(mantissa, exp, neg); ok {
  425. return f, nil
  426. }
  427. }
  428. // Try another fast path.
  429. ext := new(extFloat)
  430. if ok := ext.AssignDecimal(mantissa, exp, neg, trunc, &float32info); ok {
  431. b, ovf := ext.floatBits(&float32info)
  432. f = math.Float32frombits(uint32(b))
  433. if ovf {
  434. err = rangeError(fnParseFloat, string(s))
  435. }
  436. return f, err
  437. }
  438. }
  439. }
  440. var d decimal
  441. if !d.set(s) {
  442. return 0, syntaxError(fnParseFloat, string(s))
  443. }
  444. b, ovf := d.floatBits(&float32info)
  445. f = math.Float32frombits(uint32(b))
  446. if ovf {
  447. err = rangeError(fnParseFloat, string(s))
  448. }
  449. return f, err
  450. }
  451. func atof64(s []byte) (f float64, err error) {
  452. if val, ok := special(s); ok {
  453. return val, nil
  454. }
  455. if optimize {
  456. // Parse mantissa and exponent.
  457. mantissa, exp, neg, trunc, ok := readFloat(s)
  458. if ok {
  459. // Try pure floating-point arithmetic conversion.
  460. if !trunc {
  461. if f, ok := atof64exact(mantissa, exp, neg); ok {
  462. return f, nil
  463. }
  464. }
  465. // Try another fast path.
  466. ext := new(extFloat)
  467. if ok := ext.AssignDecimal(mantissa, exp, neg, trunc, &float64info); ok {
  468. b, ovf := ext.floatBits(&float64info)
  469. f = math.Float64frombits(b)
  470. if ovf {
  471. err = rangeError(fnParseFloat, string(s))
  472. }
  473. return f, err
  474. }
  475. }
  476. }
  477. var d decimal
  478. if !d.set(s) {
  479. return 0, syntaxError(fnParseFloat, string(s))
  480. }
  481. b, ovf := d.floatBits(&float64info)
  482. f = math.Float64frombits(b)
  483. if ovf {
  484. err = rangeError(fnParseFloat, string(s))
  485. }
  486. return f, err
  487. }
  488. // ParseFloat converts the string s to a floating-point number
  489. // with the precision specified by bitSize: 32 for float32, or 64 for float64.
  490. // When bitSize=32, the result still has type float64, but it will be
  491. // convertible to float32 without changing its value.
  492. //
  493. // If s is well-formed and near a valid floating point number,
  494. // ParseFloat returns the nearest floating point number rounded
  495. // using IEEE754 unbiased rounding.
  496. //
  497. // The errors that ParseFloat returns have concrete type *NumError
  498. // and include err.Num = s.
  499. //
  500. // If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.
  501. //
  502. // If s is syntactically well-formed but is more than 1/2 ULP
  503. // away from the largest floating point number of the given size,
  504. // ParseFloat returns f = ±Inf, err.Err = ErrRange.
  505. func ParseFloat(s []byte, bitSize int) (f float64, err error) {
  506. if bitSize == 32 {
  507. f1, err1 := atof32(s)
  508. return float64(f1), err1
  509. }
  510. f1, err1 := atof64(s)
  511. return f1, err1
  512. }
  513. // oroginal: strconv/decimal.go, but not exported, and needed for PareFloat.
  514. // Copyright 2009 The Go Authors. All rights reserved.
  515. // Use of this source code is governed by a BSD-style
  516. // license that can be found in the LICENSE file.
  517. // Multiprecision decimal numbers.
  518. // For floating-point formatting only; not general purpose.
  519. // Only operations are assign and (binary) left/right shift.
  520. // Can do binary floating point in multiprecision decimal precisely
  521. // because 2 divides 10; cannot do decimal floating point
  522. // in multiprecision binary precisely.
  523. type decimal struct {
  524. d [800]byte // digits
  525. nd int // number of digits used
  526. dp int // decimal point
  527. neg bool
  528. trunc bool // discarded nonzero digits beyond d[:nd]
  529. }
  530. func (a *decimal) String() string {
  531. n := 10 + a.nd
  532. if a.dp > 0 {
  533. n += a.dp
  534. }
  535. if a.dp < 0 {
  536. n += -a.dp
  537. }
  538. buf := make([]byte, n)
  539. w := 0
  540. switch {
  541. case a.nd == 0:
  542. return "0"
  543. case a.dp <= 0:
  544. // zeros fill space between decimal point and digits
  545. buf[w] = '0'
  546. w++
  547. buf[w] = '.'
  548. w++
  549. w += digitZero(buf[w : w+-a.dp])
  550. w += copy(buf[w:], a.d[0:a.nd])
  551. case a.dp < a.nd:
  552. // decimal point in middle of digits
  553. w += copy(buf[w:], a.d[0:a.dp])
  554. buf[w] = '.'
  555. w++
  556. w += copy(buf[w:], a.d[a.dp:a.nd])
  557. default:
  558. // zeros fill space between digits and decimal point
  559. w += copy(buf[w:], a.d[0:a.nd])
  560. w += digitZero(buf[w : w+a.dp-a.nd])
  561. }
  562. return string(buf[0:w])
  563. }
  564. func digitZero(dst []byte) int {
  565. for i := range dst {
  566. dst[i] = '0'
  567. }
  568. return len(dst)
  569. }
  570. // trim trailing zeros from number.
  571. // (They are meaningless; the decimal point is tracked
  572. // independent of the number of digits.)
  573. func trim(a *decimal) {
  574. for a.nd > 0 && a.d[a.nd-1] == '0' {
  575. a.nd--
  576. }
  577. if a.nd == 0 {
  578. a.dp = 0
  579. }
  580. }
  581. // Assign v to a.
  582. func (a *decimal) Assign(v uint64) {
  583. var buf [24]byte
  584. // Write reversed decimal in buf.
  585. n := 0
  586. for v > 0 {
  587. v1 := v / 10
  588. v -= 10 * v1
  589. buf[n] = byte(v + '0')
  590. n++
  591. v = v1
  592. }
  593. // Reverse again to produce forward decimal in a.d.
  594. a.nd = 0
  595. for n--; n >= 0; n-- {
  596. a.d[a.nd] = buf[n]
  597. a.nd++
  598. }
  599. a.dp = a.nd
  600. trim(a)
  601. }
  602. // Maximum shift that we can do in one pass without overflow.
  603. // Signed int has 31 bits, and we have to be able to accommodate 9<<k.
  604. const maxShift = 27
  605. // Binary shift right (* 2) by k bits. k <= maxShift to avoid overflow.
  606. func rightShift(a *decimal, k uint) {
  607. r := 0 // read pointer
  608. w := 0 // write pointer
  609. // Pick up enough leading digits to cover first shift.
  610. n := 0
  611. for ; n>>k == 0; r++ {
  612. if r >= a.nd {
  613. if n == 0 {
  614. // a == 0; shouldn't get here, but handle anyway.
  615. a.nd = 0
  616. return
  617. }
  618. for n>>k == 0 {
  619. n = n * 10
  620. r++
  621. }
  622. break
  623. }
  624. c := int(a.d[r])
  625. n = n*10 + c - '0'
  626. }
  627. a.dp -= r - 1
  628. // Pick up a digit, put down a digit.
  629. for ; r < a.nd; r++ {
  630. c := int(a.d[r])
  631. dig := n >> k
  632. n -= dig << k
  633. a.d[w] = byte(dig + '0')
  634. w++
  635. n = n*10 + c - '0'
  636. }
  637. // Put down extra digits.
  638. for n > 0 {
  639. dig := n >> k
  640. n -= dig << k
  641. if w < len(a.d) {
  642. a.d[w] = byte(dig + '0')
  643. w++
  644. } else if dig > 0 {
  645. a.trunc = true
  646. }
  647. n = n * 10
  648. }
  649. a.nd = w
  650. trim(a)
  651. }
  652. // Cheat sheet for left shift: table indexed by shift count giving
  653. // number of new digits that will be introduced by that shift.
  654. //
  655. // For example, leftcheats[4] = {2, "625"}. That means that
  656. // if we are shifting by 4 (multiplying by 16), it will add 2 digits
  657. // when the string prefix is "625" through "999", and one fewer digit
  658. // if the string prefix is "000" through "624".
  659. //
  660. // Credit for this trick goes to Ken.
  661. type leftCheat struct {
  662. delta int // number of new digits
  663. cutoff string // minus one digit if original < a.
  664. }
  665. var leftcheats = []leftCheat{
  666. // Leading digits of 1/2^i = 5^i.
  667. // 5^23 is not an exact 64-bit floating point number,
  668. // so have to use bc for the math.
  669. /*
  670. seq 27 | sed 's/^/5^/' | bc |
  671. awk 'BEGIN{ print "\tleftCheat{ 0, \"\" }," }
  672. {
  673. log2 = log(2)/log(10)
  674. printf("\tleftCheat{ %d, \"%s\" },\t// * %d\n",
  675. int(log2*NR+1), $0, 2**NR)
  676. }'
  677. */
  678. {0, ""},
  679. {1, "5"}, // * 2
  680. {1, "25"}, // * 4
  681. {1, "125"}, // * 8
  682. {2, "625"}, // * 16
  683. {2, "3125"}, // * 32
  684. {2, "15625"}, // * 64
  685. {3, "78125"}, // * 128
  686. {3, "390625"}, // * 256
  687. {3, "1953125"}, // * 512
  688. {4, "9765625"}, // * 1024
  689. {4, "48828125"}, // * 2048
  690. {4, "244140625"}, // * 4096
  691. {4, "1220703125"}, // * 8192
  692. {5, "6103515625"}, // * 16384
  693. {5, "30517578125"}, // * 32768
  694. {5, "152587890625"}, // * 65536
  695. {6, "762939453125"}, // * 131072
  696. {6, "3814697265625"}, // * 262144
  697. {6, "19073486328125"}, // * 524288
  698. {7, "95367431640625"}, // * 1048576
  699. {7, "476837158203125"}, // * 2097152
  700. {7, "2384185791015625"}, // * 4194304
  701. {7, "11920928955078125"}, // * 8388608
  702. {8, "59604644775390625"}, // * 16777216
  703. {8, "298023223876953125"}, // * 33554432
  704. {8, "1490116119384765625"}, // * 67108864
  705. {9, "7450580596923828125"}, // * 134217728
  706. }
  707. // Is the leading prefix of b lexicographically less than s?
  708. func prefixIsLessThan(b []byte, s string) bool {
  709. for i := 0; i < len(s); i++ {
  710. if i >= len(b) {
  711. return true
  712. }
  713. if b[i] != s[i] {
  714. return b[i] < s[i]
  715. }
  716. }
  717. return false
  718. }
  719. // Binary shift left (/ 2) by k bits. k <= maxShift to avoid overflow.
  720. func leftShift(a *decimal, k uint) {
  721. delta := leftcheats[k].delta
  722. if prefixIsLessThan(a.d[0:a.nd], leftcheats[k].cutoff) {
  723. delta--
  724. }
  725. r := a.nd // read index
  726. w := a.nd + delta // write index
  727. n := 0
  728. // Pick up a digit, put down a digit.
  729. for r--; r >= 0; r-- {
  730. n += (int(a.d[r]) - '0') << k
  731. quo := n / 10
  732. rem := n - 10*quo
  733. w--
  734. if w < len(a.d) {
  735. a.d[w] = byte(rem + '0')
  736. } else if rem != 0 {
  737. a.trunc = true
  738. }
  739. n = quo
  740. }
  741. // Put down extra digits.
  742. for n > 0 {
  743. quo := n / 10
  744. rem := n - 10*quo
  745. w--
  746. if w < len(a.d) {
  747. a.d[w] = byte(rem + '0')
  748. } else if rem != 0 {
  749. a.trunc = true
  750. }
  751. n = quo
  752. }
  753. a.nd += delta
  754. if a.nd >= len(a.d) {
  755. a.nd = len(a.d)
  756. }
  757. a.dp += delta
  758. trim(a)
  759. }
  760. // Binary shift left (k > 0) or right (k < 0).
  761. func (a *decimal) Shift(k int) {
  762. switch {
  763. case a.nd == 0:
  764. // nothing to do: a == 0
  765. case k > 0:
  766. for k > maxShift {
  767. leftShift(a, maxShift)
  768. k -= maxShift
  769. }
  770. leftShift(a, uint(k))
  771. case k < 0:
  772. for k < -maxShift {
  773. rightShift(a, maxShift)
  774. k += maxShift
  775. }
  776. rightShift(a, uint(-k))
  777. }
  778. }
  779. // If we chop a at nd digits, should we round up?
  780. func shouldRoundUp(a *decimal, nd int) bool {
  781. if nd < 0 || nd >= a.nd {
  782. return false
  783. }
  784. if a.d[nd] == '5' && nd+1 == a.nd { // exactly halfway - round to even
  785. // if we truncated, a little higher than what's recorded - always round up
  786. if a.trunc {
  787. return true
  788. }
  789. return nd > 0 && (a.d[nd-1]-'0')%2 != 0
  790. }
  791. // not halfway - digit tells all
  792. return a.d[nd] >= '5'
  793. }
  794. // Round a to nd digits (or fewer).
  795. // If nd is zero, it means we're rounding
  796. // just to the left of the digits, as in
  797. // 0.09 -> 0.1.
  798. func (a *decimal) Round(nd int) {
  799. if nd < 0 || nd >= a.nd {
  800. return
  801. }
  802. if shouldRoundUp(a, nd) {
  803. a.RoundUp(nd)
  804. } else {
  805. a.RoundDown(nd)
  806. }
  807. }
  808. // Round a down to nd digits (or fewer).
  809. func (a *decimal) RoundDown(nd int) {
  810. if nd < 0 || nd >= a.nd {
  811. return
  812. }
  813. a.nd = nd
  814. trim(a)
  815. }
  816. // Round a up to nd digits (or fewer).
  817. func (a *decimal) RoundUp(nd int) {
  818. if nd < 0 || nd >= a.nd {
  819. return
  820. }
  821. // round up
  822. for i := nd - 1; i >= 0; i-- {
  823. c := a.d[i]
  824. if c < '9' { // can stop after this digit
  825. a.d[i]++
  826. a.nd = i + 1
  827. return
  828. }
  829. }
  830. // Number is all 9s.
  831. // Change to single 1 with adjusted decimal point.
  832. a.d[0] = '1'
  833. a.nd = 1
  834. a.dp++
  835. }
  836. // Extract integer part, rounded appropriately.
  837. // No guarantees about overflow.
  838. func (a *decimal) RoundedInteger() uint64 {
  839. if a.dp > 20 {
  840. return 0xFFFFFFFFFFFFFFFF
  841. }
  842. var i int
  843. n := uint64(0)
  844. for i = 0; i < a.dp && i < a.nd; i++ {
  845. n = n*10 + uint64(a.d[i]-'0')
  846. }
  847. for ; i < a.dp; i++ {
  848. n *= 10
  849. }
  850. if shouldRoundUp(a, a.dp) {
  851. n++
  852. }
  853. return n
  854. }