Black Lives Matter. Support the Equal Justice Initiative.

Source file src/strconv/extfloat.go

Documentation: strconv

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

View as plain text