...

Source file src/math/big/ftoa.go

Documentation: math/big

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

View as plain text