PR c++/86342 - -Wdeprecated-copy and system headers.
[official-gcc.git] / libgo / go / strconv / atof.go
blobfdcb8b3d7a5c2a074332145ed53eeb7a60d1f842
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
7 // decimal to binary floating point conversion.
8 // Algorithm:
9 // 1) Store input in multiprecision decimal.
10 // 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
11 // 3) Multiply by 2^precision and round to get mantissa.
13 import "math"
14 import "runtime"
16 var optimize = true // can change for testing
18 func equalIgnoreCase(s1, s2 string) bool {
19 if len(s1) != len(s2) {
20 return false
22 for i := 0; i < len(s1); i++ {
23 c1 := s1[i]
24 if 'A' <= c1 && c1 <= 'Z' {
25 c1 += 'a' - 'A'
27 c2 := s2[i]
28 if 'A' <= c2 && c2 <= 'Z' {
29 c2 += 'a' - 'A'
31 if c1 != c2 {
32 return false
35 return true
38 func special(s string) (f float64, ok bool) {
39 if len(s) == 0 {
40 return
42 switch s[0] {
43 default:
44 return
45 case '+':
46 if equalIgnoreCase(s, "+inf") || equalIgnoreCase(s, "+infinity") {
47 return math.Inf(1), true
49 case '-':
50 if equalIgnoreCase(s, "-inf") || equalIgnoreCase(s, "-infinity") {
51 return math.Inf(-1), true
53 case 'n', 'N':
54 if equalIgnoreCase(s, "nan") {
55 return math.NaN(), true
57 case 'i', 'I':
58 if equalIgnoreCase(s, "inf") || equalIgnoreCase(s, "infinity") {
59 return math.Inf(1), true
62 return
65 func (b *decimal) set(s string) (ok bool) {
66 i := 0
67 b.neg = false
68 b.trunc = false
70 // optional sign
71 if i >= len(s) {
72 return
74 switch {
75 case s[i] == '+':
76 i++
77 case s[i] == '-':
78 b.neg = true
79 i++
82 // digits
83 sawdot := false
84 sawdigits := false
85 for ; i < len(s); i++ {
86 switch {
87 case s[i] == '.':
88 if sawdot {
89 return
91 sawdot = true
92 b.dp = b.nd
93 continue
95 case '0' <= s[i] && s[i] <= '9':
96 sawdigits = true
97 if s[i] == '0' && b.nd == 0 { // ignore leading zeros
98 b.dp--
99 continue
101 if b.nd < len(b.d) {
102 b.d[b.nd] = s[i]
103 b.nd++
104 } else if s[i] != '0' {
105 b.trunc = true
107 continue
109 break
111 if !sawdigits {
112 return
114 if !sawdot {
115 b.dp = b.nd
118 // optional exponent moves decimal point.
119 // if we read a very large, very long number,
120 // just be sure to move the decimal point by
121 // a lot (say, 100000). it doesn't matter if it's
122 // not the exact number.
123 if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
125 if i >= len(s) {
126 return
128 esign := 1
129 if s[i] == '+' {
131 } else if s[i] == '-' {
133 esign = -1
135 if i >= len(s) || s[i] < '0' || s[i] > '9' {
136 return
138 e := 0
139 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
140 if e < 10000 {
141 e = e*10 + int(s[i]) - '0'
144 b.dp += e * esign
147 if i != len(s) {
148 return
151 ok = true
152 return
155 // readFloat reads a decimal mantissa and exponent from a float
156 // string representation. It sets ok to false if the number could
157 // not fit return types or is invalid.
158 func readFloat(s string) (mantissa uint64, exp int, neg, trunc, ok bool) {
159 const uint64digits = 19
160 i := 0
162 // optional sign
163 if i >= len(s) {
164 return
166 switch {
167 case s[i] == '+':
169 case s[i] == '-':
170 neg = true
174 // digits
175 sawdot := false
176 sawdigits := false
177 nd := 0
178 ndMant := 0
179 dp := 0
180 for ; i < len(s); i++ {
181 switch c := s[i]; true {
182 case c == '.':
183 if sawdot {
184 return
186 sawdot = true
187 dp = nd
188 continue
190 case '0' <= c && c <= '9':
191 sawdigits = true
192 if c == '0' && nd == 0 { // ignore leading zeros
193 dp--
194 continue
196 nd++
197 if ndMant < uint64digits {
198 mantissa *= 10
199 mantissa += uint64(c - '0')
200 ndMant++
201 } else if s[i] != '0' {
202 trunc = true
204 continue
206 break
208 if !sawdigits {
209 return
211 if !sawdot {
212 dp = nd
215 // optional exponent moves decimal point.
216 // if we read a very large, very long number,
217 // just be sure to move the decimal point by
218 // a lot (say, 100000). it doesn't matter if it's
219 // not the exact number.
220 if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
222 if i >= len(s) {
223 return
225 esign := 1
226 if s[i] == '+' {
228 } else if s[i] == '-' {
230 esign = -1
232 if i >= len(s) || s[i] < '0' || s[i] > '9' {
233 return
235 e := 0
236 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
237 if e < 10000 {
238 e = e*10 + int(s[i]) - '0'
241 dp += e * esign
244 if i != len(s) {
245 return
248 if mantissa != 0 {
249 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) (float64, error) {
540 if bitSize == 32 {
541 f, err := atof32(s)
542 return float64(f), err
544 return atof64(s)