Fix bootstrap/PR63632
[official-gcc.git] / libgo / go / strconv / atof.go
blobbeaa68d71f544867f6e226b627061325144d07c6
1 // Copyright 2009 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.
5 // Package strconv implements conversions to and from string representations
6 // of basic data types.
7 package strconv
9 // decimal to binary floating point conversion.
10 // Algorithm:
11 // 1) Store input in multiprecision decimal.
12 // 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
13 // 3) Multiply by 2^precision and round to get mantissa.
15 import "math"
16 import "runtime"
18 var optimize = true // can change for testing
20 func equalIgnoreCase(s1, s2 string) bool {
21 if len(s1) != len(s2) {
22 return false
24 for i := 0; i < len(s1); i++ {
25 c1 := s1[i]
26 if 'A' <= c1 && c1 <= 'Z' {
27 c1 += 'a' - 'A'
29 c2 := s2[i]
30 if 'A' <= c2 && c2 <= 'Z' {
31 c2 += 'a' - 'A'
33 if c1 != c2 {
34 return false
37 return true
40 func special(s string) (f float64, ok bool) {
41 if len(s) == 0 {
42 return
44 switch s[0] {
45 default:
46 return
47 case '+':
48 if equalIgnoreCase(s, "+inf") || equalIgnoreCase(s, "+infinity") {
49 return math.Inf(1), true
51 case '-':
52 if equalIgnoreCase(s, "-inf") || equalIgnoreCase(s, "-infinity") {
53 return math.Inf(-1), true
55 case 'n', 'N':
56 if equalIgnoreCase(s, "nan") {
57 return math.NaN(), true
59 case 'i', 'I':
60 if equalIgnoreCase(s, "inf") || equalIgnoreCase(s, "infinity") {
61 return math.Inf(1), true
64 return
67 func (b *decimal) set(s string) (ok bool) {
68 i := 0
69 b.neg = false
70 b.trunc = false
72 // optional sign
73 if i >= len(s) {
74 return
76 switch {
77 case s[i] == '+':
78 i++
79 case s[i] == '-':
80 b.neg = true
81 i++
84 // digits
85 sawdot := false
86 sawdigits := false
87 for ; i < len(s); i++ {
88 switch {
89 case s[i] == '.':
90 if sawdot {
91 return
93 sawdot = true
94 b.dp = b.nd
95 continue
97 case '0' <= s[i] && s[i] <= '9':
98 sawdigits = true
99 if s[i] == '0' && b.nd == 0 { // ignore leading zeros
100 b.dp--
101 continue
103 if b.nd < len(b.d) {
104 b.d[b.nd] = s[i]
105 b.nd++
106 } else if s[i] != '0' {
107 b.trunc = true
109 continue
111 break
113 if !sawdigits {
114 return
116 if !sawdot {
117 b.dp = b.nd
120 // optional exponent moves decimal point.
121 // if we read a very large, very long number,
122 // just be sure to move the decimal point by
123 // a lot (say, 100000). it doesn't matter if it's
124 // not the exact number.
125 if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
127 if i >= len(s) {
128 return
130 esign := 1
131 if s[i] == '+' {
133 } else if s[i] == '-' {
135 esign = -1
137 if i >= len(s) || s[i] < '0' || s[i] > '9' {
138 return
140 e := 0
141 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
142 if e < 10000 {
143 e = e*10 + int(s[i]) - '0'
146 b.dp += e * esign
149 if i != len(s) {
150 return
153 ok = true
154 return
157 // readFloat reads a decimal mantissa and exponent from a float
158 // string representation. It sets ok to false if the number could
159 // not fit return types or is invalid.
160 func readFloat(s string) (mantissa uint64, exp int, neg, trunc, ok bool) {
161 const uint64digits = 19
162 i := 0
164 // optional sign
165 if i >= len(s) {
166 return
168 switch {
169 case s[i] == '+':
171 case s[i] == '-':
172 neg = true
176 // digits
177 sawdot := false
178 sawdigits := false
179 nd := 0
180 ndMant := 0
181 dp := 0
182 for ; i < len(s); i++ {
183 switch c := s[i]; true {
184 case c == '.':
185 if sawdot {
186 return
188 sawdot = true
189 dp = nd
190 continue
192 case '0' <= c && c <= '9':
193 sawdigits = true
194 if c == '0' && nd == 0 { // ignore leading zeros
195 dp--
196 continue
198 nd++
199 if ndMant < uint64digits {
200 mantissa *= 10
201 mantissa += uint64(c - '0')
202 ndMant++
203 } else if s[i] != '0' {
204 trunc = true
206 continue
208 break
210 if !sawdigits {
211 return
213 if !sawdot {
214 dp = nd
217 // optional exponent moves decimal point.
218 // if we read a very large, very long number,
219 // just be sure to move the decimal point by
220 // a lot (say, 100000). it doesn't matter if it's
221 // not the exact number.
222 if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
224 if i >= len(s) {
225 return
227 esign := 1
228 if s[i] == '+' {
230 } else if s[i] == '-' {
232 esign = -1
234 if i >= len(s) || s[i] < '0' || s[i] > '9' {
235 return
237 e := 0
238 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
239 if e < 10000 {
240 e = e*10 + int(s[i]) - '0'
243 dp += e * esign
246 if i != len(s) {
247 return
250 exp = dp - ndMant
251 ok = true
252 return
256 // decimal power of ten to binary power of two.
257 var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
259 func (d *decimal) floatBits(flt *floatInfo) (b uint64, overflow bool) {
260 var exp int
261 var mant uint64
263 // Zero is always a special case.
264 if d.nd == 0 {
265 mant = 0
266 exp = flt.bias
267 goto out
270 // Obvious overflow/underflow.
271 // These bounds are for 64-bit floats.
272 // Will have to change if we want to support 80-bit floats in the future.
273 if d.dp > 310 {
274 goto overflow
276 if d.dp < -330 {
277 // zero
278 mant = 0
279 exp = flt.bias
280 goto out
283 // Scale by powers of two until in range [0.5, 1.0)
284 exp = 0
285 for d.dp > 0 {
286 var n int
287 if d.dp >= len(powtab) {
288 n = 27
289 } else {
290 n = powtab[d.dp]
292 d.Shift(-n)
293 exp += n
295 for d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
296 var n int
297 if -d.dp >= len(powtab) {
298 n = 27
299 } else {
300 n = powtab[-d.dp]
302 d.Shift(n)
303 exp -= n
306 // Our range is [0.5,1) but floating point range is [1,2).
307 exp--
309 // Minimum representable exponent is flt.bias+1.
310 // If the exponent is smaller, move it up and
311 // adjust d accordingly.
312 if exp < flt.bias+1 {
313 n := flt.bias + 1 - exp
314 d.Shift(-n)
315 exp += n
318 if exp-flt.bias >= 1<<flt.expbits-1 {
319 goto overflow
322 // Extract 1+flt.mantbits bits.
323 d.Shift(int(1 + flt.mantbits))
324 mant = d.RoundedInteger()
326 // Rounding might have added a bit; shift down.
327 if mant == 2<<flt.mantbits {
328 mant >>= 1
329 exp++
330 if exp-flt.bias >= 1<<flt.expbits-1 {
331 goto overflow
335 // Denormalized?
336 if mant&(1<<flt.mantbits) == 0 {
337 exp = flt.bias
339 goto out
341 overflow:
342 // ±Inf
343 mant = 0
344 exp = 1<<flt.expbits - 1 + flt.bias
345 overflow = true
347 out:
348 // Assemble bits.
349 bits := mant & (uint64(1)<<flt.mantbits - 1)
350 bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits
351 if d.neg {
352 bits |= 1 << flt.mantbits << flt.expbits
354 return bits, overflow
357 // Exact powers of 10.
358 var float64pow10 = []float64{
359 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
360 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
361 1e20, 1e21, 1e22,
363 var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
365 // If possible to convert decimal representation to 64-bit float f exactly,
366 // entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
367 // Three common cases:
368 // value is exact integer
369 // value is exact integer * exact power of ten
370 // value is exact integer / exact power of ten
371 // These all produce potentially inexact but correctly rounded answers.
372 func atof64exact(mantissa uint64, exp int, neg bool) (f float64, ok bool) {
373 if mantissa>>float64info.mantbits != 0 {
374 return
376 // gccgo gets this wrong on 32-bit i386 when not using -msse.
377 // See TestRoundTrip in atof_test.go for a test case.
378 if runtime.GOARCH == "386" {
379 return
381 f = float64(mantissa)
382 if neg {
383 f = -f
385 switch {
386 case exp == 0:
387 // an integer.
388 return f, true
389 // Exact integers are <= 10^15.
390 // Exact powers of ten are <= 10^22.
391 case exp > 0 && exp <= 15+22: // int * 10^k
392 // If exponent is big but number of digits is not,
393 // can move a few zeros into the integer part.
394 if exp > 22 {
395 f *= float64pow10[exp-22]
396 exp = 22
398 if f > 1e15 || f < -1e15 {
399 // the exponent was really too large.
400 return
402 return f * float64pow10[exp], true
403 case exp < 0 && exp >= -22: // int / 10^k
404 return f / float64pow10[-exp], true
406 return
409 // If possible to compute mantissa*10^exp to 32-bit float f exactly,
410 // entirely in floating-point math, do so, avoiding the machinery above.
411 func atof32exact(mantissa uint64, exp int, neg bool) (f float32, ok bool) {
412 if mantissa>>float32info.mantbits != 0 {
413 return
415 f = float32(mantissa)
416 if neg {
417 f = -f
419 switch {
420 case exp == 0:
421 return f, true
422 // Exact integers are <= 10^7.
423 // Exact powers of ten are <= 10^10.
424 case exp > 0 && exp <= 7+10: // int * 10^k
425 // If exponent is big but number of digits is not,
426 // can move a few zeros into the integer part.
427 if exp > 10 {
428 f *= float32pow10[exp-10]
429 exp = 10
431 if f > 1e7 || f < -1e7 {
432 // the exponent was really too large.
433 return
435 return f * float32pow10[exp], true
436 case exp < 0 && exp >= -10: // int / 10^k
437 return f / float32pow10[-exp], true
439 return
442 const fnParseFloat = "ParseFloat"
444 func atof32(s string) (f float32, err error) {
445 if val, ok := special(s); ok {
446 return float32(val), nil
449 if optimize {
450 // Parse mantissa and exponent.
451 mantissa, exp, neg, trunc, ok := readFloat(s)
452 if ok {
453 // Try pure floating-point arithmetic conversion.
454 if !trunc {
455 if f, ok := atof32exact(mantissa, exp, neg); ok {
456 return f, nil
459 // Try another fast path.
460 ext := new(extFloat)
461 if ok := ext.AssignDecimal(mantissa, exp, neg, trunc, &float32info); ok {
462 b, ovf := ext.floatBits(&float32info)
463 f = math.Float32frombits(uint32(b))
464 if ovf {
465 err = rangeError(fnParseFloat, s)
467 return f, err
471 var d decimal
472 if !d.set(s) {
473 return 0, syntaxError(fnParseFloat, s)
475 b, ovf := d.floatBits(&float32info)
476 f = math.Float32frombits(uint32(b))
477 if ovf {
478 err = rangeError(fnParseFloat, s)
480 return f, err
483 func atof64(s string) (f float64, err error) {
484 if val, ok := special(s); ok {
485 return val, nil
488 if optimize {
489 // Parse mantissa and exponent.
490 mantissa, exp, neg, trunc, ok := readFloat(s)
491 if ok {
492 // Try pure floating-point arithmetic conversion.
493 if !trunc {
494 if f, ok := atof64exact(mantissa, exp, neg); ok {
495 return f, nil
498 // Try another fast path.
499 ext := new(extFloat)
500 if ok := ext.AssignDecimal(mantissa, exp, neg, trunc, &float64info); ok {
501 b, ovf := ext.floatBits(&float64info)
502 f = math.Float64frombits(b)
503 if ovf {
504 err = rangeError(fnParseFloat, s)
506 return f, err
510 var d decimal
511 if !d.set(s) {
512 return 0, syntaxError(fnParseFloat, s)
514 b, ovf := d.floatBits(&float64info)
515 f = math.Float64frombits(b)
516 if ovf {
517 err = rangeError(fnParseFloat, s)
519 return f, err
522 // ParseFloat converts the string s to a floating-point number
523 // with the precision specified by bitSize: 32 for float32, or 64 for float64.
524 // When bitSize=32, the result still has type float64, but it will be
525 // convertible to float32 without changing its value.
527 // If s is well-formed and near a valid floating point number,
528 // ParseFloat returns the nearest floating point number rounded
529 // using IEEE754 unbiased rounding.
531 // The errors that ParseFloat returns have concrete type *NumError
532 // and include err.Num = s.
534 // If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.
536 // If s is syntactically well-formed but is more than 1/2 ULP
537 // away from the largest floating point number of the given size,
538 // ParseFloat returns f = ±Inf, err.Err = ErrRange.
539 func ParseFloat(s string, bitSize int) (f float64, err error) {
540 if bitSize == 32 {
541 f1, err1 := atof32(s)
542 return float64(f1), err1
544 f1, err1 := atof64(s)
545 return f1, err1