# Source file src/math/big/floatconv.go

```     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 string-to-Float conversion functions.
6
7  package big
8
9  import (
10  	"fmt"
11  	"io"
12  	"strings"
13  )
14
15  var floatZero Float
16
17  // SetString sets z to the value of s and returns z and a boolean indicating
18  // success. s must be a floating-point number of the same format as accepted
19  // by [Float.Parse], with base argument 0. The entire string (not just a prefix) must
20  // be valid for success. If the operation failed, the value of z is undefined
21  // but the returned value is nil.
22  func (z *Float) SetString(s string) (*Float, bool) {
23  	if f, _, err := z.Parse(s, 0); err == nil {
24  		return f, true
25  	}
26  	return nil, false
27  }
28
29  // scan is like Parse but reads the longest possible prefix representing a valid
30  // floating point number from an io.ByteScanner rather than a string. It serves
31  // as the implementation of Parse. It does not recognize ±Inf and does not expect
32  // EOF at the end.
33  func (z *Float) scan(r io.ByteScanner, base int) (f *Float, b int, err error) {
34  	prec := z.prec
35  	if prec == 0 {
36  		prec = 64
37  	}
38
39  	// A reasonable value in case of an error.
40  	z.form = zero
41
42  	// sign
43  	z.neg, err = scanSign(r)
44  	if err != nil {
45  		return
46  	}
47
48  	// mantissa
49  	var fcount int // fractional digit count; valid if <= 0
50  	z.mant, b, fcount, err = z.mant.scan(r, base, true)
51  	if err != nil {
52  		return
53  	}
54
55  	// exponent
56  	var exp int64
57  	var ebase int
58  	exp, ebase, err = scanExponent(r, true, base == 0)
59  	if err != nil {
60  		return
61  	}
62
63  	// special-case 0
64  	if len(z.mant) == 0 {
65  		z.prec = prec
66  		z.acc = Exact
67  		z.form = zero
68  		f = z
69  		return
70  	}
71  	// len(z.mant) > 0
72
73  	// The mantissa may have a radix point (fcount <= 0) and there
74  	// may be a nonzero exponent exp. The radix point amounts to a
75  	// division by b**(-fcount). An exponent means multiplication by
76  	// ebase**exp. Finally, mantissa normalization (shift left) requires
77  	// a correcting multiplication by 2**(-shiftcount). Multiplications
78  	// are commutative, so we can apply them in any order as long as there
79  	// is no loss of precision. We only have powers of 2 and 10, and
80  	// we split powers of 10 into the product of the same powers of
81  	// 2 and 5. This reduces the size of the multiplication factor
82  	// needed for base-10 exponents.
83
84  	// normalize mantissa and determine initial exponent contributions
85  	exp2 := int64(len(z.mant))*_W - fnorm(z.mant)
86  	exp5 := int64(0)
87
88  	// determine binary or decimal exponent contribution of radix point
89  	if fcount < 0 {
90  		// The mantissa has a radix point ddd.dddd; and
91  		// -fcount is the number of digits to the right
92  		// of '.'. Adjust relevant exponent accordingly.
93  		d := int64(fcount)
94  		switch b {
95  		case 10:
96  			exp5 = d
97  			fallthrough // 10**e == 5**e * 2**e
98  		case 2:
99  			exp2 += d
100  		case 8:
101  			exp2 += d * 3 // octal digits are 3 bits each
102  		case 16:
103  			exp2 += d * 4 // hexadecimal digits are 4 bits each
104  		default:
105  			panic("unexpected mantissa base")
106  		}
107  		// fcount consumed - not needed anymore
108  	}
109
110  	// take actual exponent into account
111  	switch ebase {
112  	case 10:
113  		exp5 += exp
114  		fallthrough // see fallthrough above
115  	case 2:
116  		exp2 += exp
117  	default:
118  		panic("unexpected exponent base")
119  	}
120  	// exp consumed - not needed anymore
121
122  	// apply 2**exp2
123  	if MinExp <= exp2 && exp2 <= MaxExp {
124  		z.prec = prec
125  		z.form = finite
126  		z.exp = int32(exp2)
127  		f = z
128  	} else {
129  		err = fmt.Errorf("exponent overflow")
130  		return
131  	}
132
133  	if exp5 == 0 {
134  		// no decimal exponent contribution
135  		z.round(0)
136  		return
137  	}
138  	// exp5 != 0
139
140  	// apply 5**exp5
141  	p := new(Float).SetPrec(z.Prec() + 64) // use more bits for p -- TODO(gri) what is the right number?
142  	if exp5 < 0 {
143  		z.Quo(z, p.pow5(uint64(-exp5)))
144  	} else {
145  		z.Mul(z, p.pow5(uint64(exp5)))
146  	}
147
148  	return
149  }
150
151  // These powers of 5 fit into a uint64.
152  //
153  //	for p, q := uint64(0), uint64(1); p < q; p, q = q, q*5 {
154  //		fmt.Println(q)
155  //	}
156  var pow5tab = [...]uint64{
157  	1,
158  	5,
159  	25,
160  	125,
161  	625,
162  	3125,
163  	15625,
164  	78125,
165  	390625,
166  	1953125,
167  	9765625,
168  	48828125,
169  	244140625,
170  	1220703125,
171  	6103515625,
172  	30517578125,
173  	152587890625,
174  	762939453125,
175  	3814697265625,
176  	19073486328125,
177  	95367431640625,
178  	476837158203125,
179  	2384185791015625,
180  	11920928955078125,
181  	59604644775390625,
182  	298023223876953125,
183  	1490116119384765625,
184  	7450580596923828125,
185  }
186
187  // pow5 sets z to 5**n and returns z.
188  // n must not be negative.
189  func (z *Float) pow5(n uint64) *Float {
190  	const m = uint64(len(pow5tab) - 1)
191  	if n <= m {
192  		return z.SetUint64(pow5tab[n])
193  	}
194  	// n > m
195
196  	z.SetUint64(pow5tab[m])
197  	n -= m
198
199  	// use more bits for f than for z
200  	// TODO(gri) what is the right number?
201  	f := new(Float).SetPrec(z.Prec() + 64).SetUint64(5)
202
203  	for n > 0 {
204  		if n&1 != 0 {
205  			z.Mul(z, f)
206  		}
207  		f.Mul(f, f)
208  		n >>= 1
209  	}
210
211  	return z
212  }
213
214  // Parse parses s which must contain a text representation of a floating-
215  // point number with a mantissa in the given conversion base (the exponent
216  // is always a decimal number), or a string representing an infinite value.
217  //
218  // For base 0, an underscore character “_” may appear between a base
219  // prefix and an adjacent digit, and between successive digits; such
220  // underscores do not change the value of the number, or the returned
221  // digit count. Incorrect placement of underscores is reported as an
222  // error if there are no other errors. If base != 0, underscores are
223  // not recognized and thus terminate scanning like any other character
224  // that is not a valid radix point or digit.
225  //
226  // It sets z to the (possibly rounded) value of the corresponding floating-
227  // point value, and returns z, the actual base b, and an error err, if any.
228  // The entire string (not just a prefix) must be consumed for success.
229  // If z's precision is 0, it is changed to 64 before rounding takes effect.
230  // The number must be of the form:
231  //
232  //	number    = [ sign ] ( float | "inf" | "Inf" ) .
233  //	sign      = "+" | "-" .
234  //	float     = ( mantissa | prefix pmantissa ) [ exponent ] .
235  //	prefix    = "0" [ "b" | "B" | "o" | "O" | "x" | "X" ] .
236  //	mantissa  = digits "." [ digits ] | digits | "." digits .
237  //	pmantissa = [ "_" ] digits "." [ digits ] | [ "_" ] digits | "." digits .
238  //	exponent  = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
239  //	digits    = digit { [ "_" ] digit } .
240  //	digit     = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
241  //
242  // The base argument must be 0, 2, 8, 10, or 16. Providing an invalid base
243  // argument will lead to a run-time panic.
244  //
245  // For base 0, the number prefix determines the actual base: A prefix of
246  // “0b” or “0B” selects base 2, “0o” or “0O” selects base 8, and
247  // “0x” or “0X” selects base 16. Otherwise, the actual base is 10 and
248  // no prefix is accepted. The octal prefix "0" is not supported (a leading
249  // "0" is simply considered a "0").
250  //
251  // A "p" or "P" exponent indicates a base 2 (rather than base 10) exponent;
252  // for instance, "0x1.fffffffffffffp1023" (using base 0) represents the
253  // maximum float64 value. For hexadecimal mantissae, the exponent character
254  // must be one of 'p' or 'P', if present (an "e" or "E" exponent indicator
255  // cannot be distinguished from a mantissa digit).
256  //
257  // The returned *Float f is nil and the value of z is valid but not
258  // defined if an error is reported.
259  func (z *Float) Parse(s string, base int) (f *Float, b int, err error) {
260  	// scan doesn't handle ±Inf
261  	if len(s) == 3 && (s == "Inf" || s == "inf") {
262  		f = z.SetInf(false)
263  		return
264  	}
265  	if len(s) == 4 && (s[0] == '+' || s[0] == '-') && (s[1:] == "Inf" || s[1:] == "inf") {
266  		f = z.SetInf(s[0] == '-')
267  		return
268  	}
269
270  	r := strings.NewReader(s)
271  	if f, b, err = z.scan(r, base); err != nil {
272  		return
273  	}
274
275  	// entire string must have been consumed
276  	if ch, err2 := r.ReadByte(); err2 == nil {
277  		err = fmt.Errorf("expected end of string, found %q", ch)
278  	} else if err2 != io.EOF {
279  		err = err2
280  	}
281
282  	return
283  }
284
285  // ParseFloat is like f.Parse(s, base) with f set to the given precision
286  // and rounding mode.
287  func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error) {
288  	return new(Float).SetPrec(prec).SetMode(mode).Parse(s, base)
289  }
290
291  var _ fmt.Scanner = (*Float)(nil) // *Float must implement fmt.Scanner
292
293  // Scan is a support routine for [fmt.Scanner]; it sets z to the value of
294  // the scanned number. It accepts formats whose verbs are supported by
295  // [fmt.Scan] for floating point values, which are:
296  // 'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'.
297  // Scan doesn't handle ±Inf.
298  func (z *Float) Scan(s fmt.ScanState, ch rune) error {
299  	s.SkipSpace()
300  	_, _, err := z.scan(byteReader{s}, 0)
301  	return err
302  }
303
```

View as plain text