ftoa.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. // Copyright 2015 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. // This file implements Float-to-string conversion functions.
  5. // It is closely following the corresponding implementation
  6. // in strconv/ftoa.go, but modified and simplified for Float.
  7. package big
  8. import (
  9. "bytes"
  10. "fmt"
  11. "strconv"
  12. )
  13. // Text converts the floating-point number x to a string according
  14. // to the given format and precision prec. The format is one of:
  15. //
  16. // 'e' -d.dddde±dd, decimal exponent, at least two (possibly 0) exponent digits
  17. // 'E' -d.ddddE±dd, decimal exponent, at least two (possibly 0) exponent digits
  18. // 'f' -ddddd.dddd, no exponent
  19. // 'g' like 'e' for large exponents, like 'f' otherwise
  20. // 'G' like 'E' for large exponents, like 'f' otherwise
  21. // 'x' -0xd.dddddp±dd, hexadecimal mantissa, decimal power of two exponent
  22. // 'p' -0x.dddp±dd, hexadecimal mantissa, decimal power of two exponent (non-standard)
  23. // 'b' -ddddddp±dd, decimal mantissa, decimal power of two exponent (non-standard)
  24. //
  25. // For the power-of-two exponent formats, the mantissa is printed in normalized form:
  26. //
  27. // 'x' hexadecimal mantissa in [1, 2), or 0
  28. // 'p' hexadecimal mantissa in [½, 1), or 0
  29. // 'b' decimal integer mantissa using x.Prec() bits, or 0
  30. //
  31. // Note that the 'x' form is the one used by most other languages and libraries.
  32. //
  33. // If format is a different character, Text returns a "%" followed by the
  34. // unrecognized format character.
  35. //
  36. // The precision prec controls the number of digits (excluding the exponent)
  37. // printed by the 'e', 'E', 'f', 'g', 'G', and 'x' formats.
  38. // For 'e', 'E', 'f', and 'x', it is the number of digits after the decimal point.
  39. // For 'g' and 'G' it is the total number of digits. A negative precision selects
  40. // the smallest number of decimal digits necessary to identify the value x uniquely
  41. // using x.Prec() mantissa bits.
  42. // The prec value is ignored for the 'b' and 'p' formats.
  43. func (x *Float) Text(format byte, prec int) string {
  44. cap := 10 // TODO(gri) determine a good/better value here
  45. if prec > 0 {
  46. cap += prec
  47. }
  48. return string(x.Append(make([]byte, 0, cap), format, prec))
  49. }
  50. // String formats x like x.Text('g', 10).
  51. // (String must be called explicitly, Float.Format does not support %s verb.)
  52. func (x *Float) String() string {
  53. return x.Text('g', 10)
  54. }
  55. // Append appends to buf the string form of the floating-point number x,
  56. // as generated by x.Text, and returns the extended buffer.
  57. func (x *Float) Append(buf []byte, fmt byte, prec int) []byte {
  58. // sign
  59. if x.neg {
  60. buf = append(buf, '-')
  61. }
  62. // Inf
  63. if x.form == inf {
  64. if !x.neg {
  65. buf = append(buf, '+')
  66. }
  67. return append(buf, "Inf"...)
  68. }
  69. // pick off easy formats
  70. switch fmt {
  71. case 'b':
  72. return x.fmtB(buf)
  73. case 'p':
  74. return x.fmtP(buf)
  75. case 'x':
  76. return x.fmtX(buf, prec)
  77. }
  78. // Algorithm:
  79. // 1) convert Float to multiprecision decimal
  80. // 2) round to desired precision
  81. // 3) read digits out and format
  82. // 1) convert Float to multiprecision decimal
  83. var d decimal // == 0.0
  84. if x.form == finite {
  85. // x != 0
  86. d.init(x.mant, int(x.exp)-x.mant.bitLen())
  87. }
  88. // 2) round to desired precision
  89. shortest := false
  90. if prec < 0 {
  91. shortest = true
  92. roundShortest(&d, x)
  93. // Precision for shortest representation mode.
  94. switch fmt {
  95. case 'e', 'E':
  96. prec = len(d.mant) - 1
  97. case 'f':
  98. prec = max(len(d.mant)-d.exp, 0)
  99. case 'g', 'G':
  100. prec = len(d.mant)
  101. }
  102. } else {
  103. // round appropriately
  104. switch fmt {
  105. case 'e', 'E':
  106. // one digit before and number of digits after decimal point
  107. d.round(1 + prec)
  108. case 'f':
  109. // number of digits before and after decimal point
  110. d.round(d.exp + prec)
  111. case 'g', 'G':
  112. if prec == 0 {
  113. prec = 1
  114. }
  115. d.round(prec)
  116. }
  117. }
  118. // 3) read digits out and format
  119. switch fmt {
  120. case 'e', 'E':
  121. return fmtE(buf, fmt, prec, d)
  122. case 'f':
  123. return fmtF(buf, prec, d)
  124. case 'g', 'G':
  125. // trim trailing fractional zeros in %e format
  126. eprec := prec
  127. if eprec > len(d.mant) && len(d.mant) >= d.exp {
  128. eprec = len(d.mant)
  129. }
  130. // %e is used if the exponent from the conversion
  131. // is less than -4 or greater than or equal to the precision.
  132. // If precision was the shortest possible, use eprec = 6 for
  133. // this decision.
  134. if shortest {
  135. eprec = 6
  136. }
  137. exp := d.exp - 1
  138. if exp < -4 || exp >= eprec {
  139. if prec > len(d.mant) {
  140. prec = len(d.mant)
  141. }
  142. return fmtE(buf, fmt+'e'-'g', prec-1, d)
  143. }
  144. if prec > d.exp {
  145. prec = len(d.mant)
  146. }
  147. return fmtF(buf, max(prec-d.exp, 0), d)
  148. }
  149. // unknown format
  150. if x.neg {
  151. buf = buf[:len(buf)-1] // sign was added prematurely - remove it again
  152. }
  153. return append(buf, '%', fmt)
  154. }
  155. func roundShortest(d *decimal, x *Float) {
  156. // if the mantissa is zero, the number is zero - stop now
  157. if len(d.mant) == 0 {
  158. return
  159. }
  160. // Approach: All numbers in the interval [x - 1/2ulp, x + 1/2ulp]
  161. // (possibly exclusive) round to x for the given precision of x.
  162. // Compute the lower and upper bound in decimal form and find the
  163. // shortest decimal number d such that lower <= d <= upper.
  164. // TODO(gri) strconv/ftoa.do describes a shortcut in some cases.
  165. // See if we can use it (in adjusted form) here as well.
  166. // 1) Compute normalized mantissa mant and exponent exp for x such
  167. // that the lsb of mant corresponds to 1/2 ulp for the precision of
  168. // x (i.e., for mant we want x.prec + 1 bits).
  169. mant := nat(nil).set(x.mant)
  170. exp := int(x.exp) - mant.bitLen()
  171. s := mant.bitLen() - int(x.prec+1)
  172. switch {
  173. case s < 0:
  174. mant = mant.shl(mant, uint(-s))
  175. case s > 0:
  176. mant = mant.shr(mant, uint(+s))
  177. }
  178. exp += s
  179. // x = mant * 2**exp with lsb(mant) == 1/2 ulp of x.prec
  180. // 2) Compute lower bound by subtracting 1/2 ulp.
  181. var lower decimal
  182. var tmp nat
  183. lower.init(tmp.sub(mant, natOne), exp)
  184. // 3) Compute upper bound by adding 1/2 ulp.
  185. var upper decimal
  186. upper.init(tmp.add(mant, natOne), exp)
  187. // The upper and lower bounds are possible outputs only if
  188. // the original mantissa is even, so that ToNearestEven rounding
  189. // would round to the original mantissa and not the neighbors.
  190. inclusive := mant[0]&2 == 0 // test bit 1 since original mantissa was shifted by 1
  191. // Now we can figure out the minimum number of digits required.
  192. // Walk along until d has distinguished itself from upper and lower.
  193. for i, m := range d.mant {
  194. l := lower.at(i)
  195. u := upper.at(i)
  196. // Okay to round down (truncate) if lower has a different digit
  197. // or if lower is inclusive and is exactly the result of rounding
  198. // down (i.e., and we have reached the final digit of lower).
  199. okdown := l != m || inclusive && i+1 == len(lower.mant)
  200. // Okay to round up if upper has a different digit and either upper
  201. // is inclusive or upper is bigger than the result of rounding up.
  202. okup := m != u && (inclusive || m+1 < u || i+1 < len(upper.mant))
  203. // If it's okay to do either, then round to the nearest one.
  204. // If it's okay to do only one, do it.
  205. switch {
  206. case okdown && okup:
  207. d.round(i + 1)
  208. return
  209. case okdown:
  210. d.roundDown(i + 1)
  211. return
  212. case okup:
  213. d.roundUp(i + 1)
  214. return
  215. }
  216. }
  217. }
  218. // %e: d.ddddde±dd
  219. func fmtE(buf []byte, fmt byte, prec int, d decimal) []byte {
  220. // first digit
  221. ch := byte('0')
  222. if len(d.mant) > 0 {
  223. ch = d.mant[0]
  224. }
  225. buf = append(buf, ch)
  226. // .moredigits
  227. if prec > 0 {
  228. buf = append(buf, '.')
  229. i := 1
  230. m := min(len(d.mant), prec+1)
  231. if i < m {
  232. buf = append(buf, d.mant[i:m]...)
  233. i = m
  234. }
  235. for ; i <= prec; i++ {
  236. buf = append(buf, '0')
  237. }
  238. }
  239. // e±
  240. buf = append(buf, fmt)
  241. var exp int64
  242. if len(d.mant) > 0 {
  243. exp = int64(d.exp) - 1 // -1 because first digit was printed before '.'
  244. }
  245. if exp < 0 {
  246. ch = '-'
  247. exp = -exp
  248. } else {
  249. ch = '+'
  250. }
  251. buf = append(buf, ch)
  252. // dd...d
  253. if exp < 10 {
  254. buf = append(buf, '0') // at least 2 exponent digits
  255. }
  256. return strconv.AppendInt(buf, exp, 10)
  257. }
  258. // %f: ddddddd.ddddd
  259. func fmtF(buf []byte, prec int, d decimal) []byte {
  260. // integer, padded with zeros as needed
  261. if d.exp > 0 {
  262. m := min(len(d.mant), d.exp)
  263. buf = append(buf, d.mant[:m]...)
  264. for ; m < d.exp; m++ {
  265. buf = append(buf, '0')
  266. }
  267. } else {
  268. buf = append(buf, '0')
  269. }
  270. // fraction
  271. if prec > 0 {
  272. buf = append(buf, '.')
  273. for i := 0; i < prec; i++ {
  274. buf = append(buf, d.at(d.exp+i))
  275. }
  276. }
  277. return buf
  278. }
  279. // fmtB appends the string of x in the format mantissa "p" exponent
  280. // with a decimal mantissa and a binary exponent, or 0" if x is zero,
  281. // and returns the extended buffer.
  282. // The mantissa is normalized such that is uses x.Prec() bits in binary
  283. // representation.
  284. // The sign of x is ignored, and x must not be an Inf.
  285. // (The caller handles Inf before invoking fmtB.)
  286. func (x *Float) fmtB(buf []byte) []byte {
  287. if x.form == zero {
  288. return append(buf, '0')
  289. }
  290. if debugFloat && x.form != finite {
  291. panic("non-finite float")
  292. }
  293. // x != 0
  294. // adjust mantissa to use exactly x.prec bits
  295. m := x.mant
  296. switch w := uint32(len(x.mant)) * _W; {
  297. case w < x.prec:
  298. m = nat(nil).shl(m, uint(x.prec-w))
  299. case w > x.prec:
  300. m = nat(nil).shr(m, uint(w-x.prec))
  301. }
  302. buf = append(buf, m.utoa(10)...)
  303. buf = append(buf, 'p')
  304. e := int64(x.exp) - int64(x.prec)
  305. if e >= 0 {
  306. buf = append(buf, '+')
  307. }
  308. return strconv.AppendInt(buf, e, 10)
  309. }
  310. // fmtX appends the string of x in the format "0x1." mantissa "p" exponent
  311. // with a hexadecimal mantissa and a binary exponent, or "0x0p0" if x is zero,
  312. // and returns the extended buffer.
  313. // A non-zero mantissa is normalized such that 1.0 <= mantissa < 2.0.
  314. // The sign of x is ignored, and x must not be an Inf.
  315. // (The caller handles Inf before invoking fmtX.)
  316. func (x *Float) fmtX(buf []byte, prec int) []byte {
  317. if x.form == zero {
  318. buf = append(buf, "0x0"...)
  319. if prec > 0 {
  320. buf = append(buf, '.')
  321. for i := 0; i < prec; i++ {
  322. buf = append(buf, '0')
  323. }
  324. }
  325. buf = append(buf, "p+00"...)
  326. return buf
  327. }
  328. if debugFloat && x.form != finite {
  329. panic("non-finite float")
  330. }
  331. // round mantissa to n bits
  332. var n uint
  333. if prec < 0 {
  334. n = 1 + (x.MinPrec()-1+3)/4*4 // round MinPrec up to 1 mod 4
  335. } else {
  336. n = 1 + 4*uint(prec)
  337. }
  338. // n%4 == 1
  339. x = new(Float).SetPrec(n).SetMode(x.mode).Set(x)
  340. // adjust mantissa to use exactly n bits
  341. m := x.mant
  342. switch w := uint(len(x.mant)) * _W; {
  343. case w < n:
  344. m = nat(nil).shl(m, n-w)
  345. case w > n:
  346. m = nat(nil).shr(m, w-n)
  347. }
  348. exp64 := int64(x.exp) - 1 // avoid wrap-around
  349. hm := m.utoa(16)
  350. if debugFloat && hm[0] != '1' {
  351. panic("incorrect mantissa: " + string(hm))
  352. }
  353. buf = append(buf, "0x1"...)
  354. if len(hm) > 1 {
  355. buf = append(buf, '.')
  356. buf = append(buf, hm[1:]...)
  357. }
  358. buf = append(buf, 'p')
  359. if exp64 >= 0 {
  360. buf = append(buf, '+')
  361. } else {
  362. exp64 = -exp64
  363. buf = append(buf, '-')
  364. }
  365. // Force at least two exponent digits, to match fmt.
  366. if exp64 < 10 {
  367. buf = append(buf, '0')
  368. }
  369. return strconv.AppendInt(buf, exp64, 10)
  370. }
  371. // fmtP appends the string of x in the format "0x." mantissa "p" exponent
  372. // with a hexadecimal mantissa and a binary exponent, or "0" if x is zero,
  373. // and returns the extended buffer.
  374. // The mantissa is normalized such that 0.5 <= 0.mantissa < 1.0.
  375. // The sign of x is ignored, and x must not be an Inf.
  376. // (The caller handles Inf before invoking fmtP.)
  377. func (x *Float) fmtP(buf []byte) []byte {
  378. if x.form == zero {
  379. return append(buf, '0')
  380. }
  381. if debugFloat && x.form != finite {
  382. panic("non-finite float")
  383. }
  384. // x != 0
  385. // remove trailing 0 words early
  386. // (no need to convert to hex 0's and trim later)
  387. m := x.mant
  388. i := 0
  389. for i < len(m) && m[i] == 0 {
  390. i++
  391. }
  392. m = m[i:]
  393. buf = append(buf, "0x."...)
  394. buf = append(buf, bytes.TrimRight(m.utoa(16), "0")...)
  395. buf = append(buf, 'p')
  396. if x.exp >= 0 {
  397. buf = append(buf, '+')
  398. }
  399. return strconv.AppendInt(buf, int64(x.exp), 10)
  400. }
  401. func min(x, y int) int {
  402. if x < y {
  403. return x
  404. }
  405. return y
  406. }
  407. var _ fmt.Formatter = &floatZero // *Float must implement fmt.Formatter
  408. // Format implements fmt.Formatter. It accepts all the regular
  409. // formats for floating-point numbers ('b', 'e', 'E', 'f', 'F',
  410. // 'g', 'G', 'x') as well as 'p' and 'v'. See (*Float).Text for the
  411. // interpretation of 'p'. The 'v' format is handled like 'g'.
  412. // Format also supports specification of the minimum precision
  413. // in digits, the output field width, as well as the format flags
  414. // '+' and ' ' for sign control, '0' for space or zero padding,
  415. // and '-' for left or right justification. See the fmt package
  416. // for details.
  417. func (x *Float) Format(s fmt.State, format rune) {
  418. prec, hasPrec := s.Precision()
  419. if !hasPrec {
  420. prec = 6 // default precision for 'e', 'f'
  421. }
  422. switch format {
  423. case 'e', 'E', 'f', 'b', 'p', 'x':
  424. // nothing to do
  425. case 'F':
  426. // (*Float).Text doesn't support 'F'; handle like 'f'
  427. format = 'f'
  428. case 'v':
  429. // handle like 'g'
  430. format = 'g'
  431. fallthrough
  432. case 'g', 'G':
  433. if !hasPrec {
  434. prec = -1 // default precision for 'g', 'G'
  435. }
  436. default:
  437. fmt.Fprintf(s, "%%!%c(*big.Float=%s)", format, x.String())
  438. return
  439. }
  440. var buf []byte
  441. buf = x.Append(buf, byte(format), prec)
  442. if len(buf) == 0 {
  443. buf = []byte("?") // should never happen, but don't crash
  444. }
  445. // len(buf) > 0
  446. var sign string
  447. switch {
  448. case buf[0] == '-':
  449. sign = "-"
  450. buf = buf[1:]
  451. case buf[0] == '+':
  452. // +Inf
  453. sign = "+"
  454. if s.Flag(' ') {
  455. sign = " "
  456. }
  457. buf = buf[1:]
  458. case s.Flag('+'):
  459. sign = "+"
  460. case s.Flag(' '):
  461. sign = " "
  462. }
  463. var padding int
  464. if width, hasWidth := s.Width(); hasWidth && width > len(sign)+len(buf) {
  465. padding = width - len(sign) - len(buf)
  466. }
  467. switch {
  468. case s.Flag('0') && !x.IsInf():
  469. // 0-padding on left
  470. writeMultiple(s, sign, 1)
  471. writeMultiple(s, "0", padding)
  472. s.Write(buf)
  473. case s.Flag('-'):
  474. // padding on right
  475. writeMultiple(s, sign, 1)
  476. s.Write(buf)
  477. writeMultiple(s, " ", padding)
  478. default:
  479. // padding on left
  480. writeMultiple(s, " ", padding)
  481. writeMultiple(s, sign, 1)
  482. s.Write(buf)
  483. }
  484. }