...

Source file src/pkg/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 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	//
   157	var pow5tab = [...]uint64{
   158		1,
   159		5,
   160		25,
   161		125,
   162		625,
   163		3125,
   164		15625,
   165		78125,
   166		390625,
   167		1953125,
   168		9765625,
   169		48828125,
   170		244140625,
   171		1220703125,
   172		6103515625,
   173		30517578125,
   174		152587890625,
   175		762939453125,
   176		3814697265625,
   177		19073486328125,
   178		95367431640625,
   179		476837158203125,
   180		2384185791015625,
   181		11920928955078125,
   182		59604644775390625,
   183		298023223876953125,
   184		1490116119384765625,
   185		7450580596923828125,
   186	}
   187	
   188	// pow5 sets z to 5**n and returns z.
   189	// n must not be negative.
   190	func (z *Float) pow5(n uint64) *Float {
   191		const m = uint64(len(pow5tab) - 1)
   192		if n <= m {
   193			return z.SetUint64(pow5tab[n])
   194		}
   195		// n > m
   196	
   197		z.SetUint64(pow5tab[m])
   198		n -= m
   199	
   200		// use more bits for f than for z
   201		// TODO(gri) what is the right number?
   202		f := new(Float).SetPrec(z.Prec() + 64).SetUint64(5)
   203	
   204		for n > 0 {
   205			if n&1 != 0 {
   206				z.Mul(z, f)
   207			}
   208			f.Mul(f, f)
   209			n >>= 1
   210		}
   211	
   212		return z
   213	}
   214	
   215	// Parse parses s which must contain a text representation of a floating-
   216	// point number with a mantissa in the given conversion base (the exponent
   217	// is always a decimal number), or a string representing an infinite value.
   218	//
   219	// For base 0, an underscore character ``_'' may appear between a base
   220	// prefix and an adjacent digit, and between successive digits; such
   221	// underscores do not change the value of the number, or the returned
   222	// digit count. Incorrect placement of underscores is reported as an
   223	// error if there are no other errors. If base != 0, underscores are
   224	// not recognized and thus terminate scanning like any other character
   225	// that is not a valid radix point or digit.
   226	//
   227	// It sets z to the (possibly rounded) value of the corresponding floating-
   228	// point value, and returns z, the actual base b, and an error err, if any.
   229	// The entire string (not just a prefix) must be consumed for success.
   230	// If z's precision is 0, it is changed to 64 before rounding takes effect.
   231	// The number must be of the form:
   232	//
   233	//     number    = [ sign ] ( float | "inf" | "Inf" ) .
   234	//     sign      = "+" | "-" .
   235	//     float     = ( mantissa | prefix pmantissa ) [ exponent ] .
   236	//     prefix    = "0" [ "b" | "B" | "o" | "O" | "x" | "X" ] .
   237	//     mantissa  = digits "." [ digits ] | digits | "." digits .
   238	//     pmantissa = [ "_" ] digits "." [ digits ] | [ "_" ] digits | "." digits .
   239	//     exponent  = ( "e" | "E" | "p" | "P" ) [ sign ] digits .
   240	//     digits    = digit { [ "_" ] digit } .
   241	//     digit     = "0" ... "9" | "a" ... "z" | "A" ... "Z" .
   242	//
   243	// The base argument must be 0, 2, 8, 10, or 16. Providing an invalid base
   244	// argument will lead to a run-time panic.
   245	//
   246	// For base 0, the number prefix determines the actual base: A prefix of
   247	// ``0b'' or ``0B'' selects base 2, ``0o'' or ``0O'' selects base 8, and
   248	// ``0x'' or ``0X'' selects base 16. Otherwise, the actual base is 10 and
   249	// no prefix is accepted. The octal prefix "0" is not supported (a leading
   250	// "0" is simply considered a "0").
   251	//
   252	// A "p" or "P" exponent indicates a base 2 (rather then base 10) exponent;
   253	// for instance, "0x1.fffffffffffffp1023" (using base 0) represents the
   254	// maximum float64 value. For hexadecimal mantissae, the exponent character
   255	// must be one of 'p' or 'P', if present (an "e" or "E" exponent indicator
   256	// cannot be distinguished from a mantissa digit).
   257	//
   258	// The returned *Float f is nil and the value of z is valid but not
   259	// defined if an error is reported.
   260	//
   261	func (z *Float) Parse(s string, base int) (f *Float, b int, err error) {
   262		// scan doesn't handle ±Inf
   263		if len(s) == 3 && (s == "Inf" || s == "inf") {
   264			f = z.SetInf(false)
   265			return
   266		}
   267		if len(s) == 4 && (s[0] == '+' || s[0] == '-') && (s[1:] == "Inf" || s[1:] == "inf") {
   268			f = z.SetInf(s[0] == '-')
   269			return
   270		}
   271	
   272		r := strings.NewReader(s)
   273		if f, b, err = z.scan(r, base); err != nil {
   274			return
   275		}
   276	
   277		// entire string must have been consumed
   278		if ch, err2 := r.ReadByte(); err2 == nil {
   279			err = fmt.Errorf("expected end of string, found %q", ch)
   280		} else if err2 != io.EOF {
   281			err = err2
   282		}
   283	
   284		return
   285	}
   286	
   287	// ParseFloat is like f.Parse(s, base) with f set to the given precision
   288	// and rounding mode.
   289	func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error) {
   290		return new(Float).SetPrec(prec).SetMode(mode).Parse(s, base)
   291	}
   292	
   293	var _ fmt.Scanner = &floatZero // *Float must implement fmt.Scanner
   294	
   295	// Scan is a support routine for fmt.Scanner; it sets z to the value of
   296	// the scanned number. It accepts formats whose verbs are supported by
   297	// fmt.Scan for floating point values, which are:
   298	// 'b' (binary), 'e', 'E', 'f', 'F', 'g' and 'G'.
   299	// Scan doesn't handle ±Inf.
   300	func (z *Float) Scan(s fmt.ScanState, ch rune) error {
   301		s.SkipSpace()
   302		_, _, err := z.scan(byteReader{s}, 0)
   303		return err
   304	}
   305	

View as plain text