Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / strconv / atof.go
blob262a8b53c7259b668756b4402888afea41ae7b9f
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 // decimal to binary floating point conversion.
6 // Algorithm:
7 // 1) Store input in multiprecision decimal.
8 // 2) Multiply/divide decimal by powers of two until in range [0.5, 1)
9 // 3) Multiply by 2^precision and round to get mantissa.
11 // The strconv package implements conversions to and from
12 // string representations of basic data types.
13 package strconv
15 import (
16 "math"
17 "os"
20 var optimize = true // can change for testing
22 // TODO(rsc): Better truncation handling.
23 func stringToDecimal(s string) (neg bool, d *decimal, trunc bool, ok bool) {
24 i := 0
26 // optional sign
27 if i >= len(s) {
28 return
30 switch {
31 case s[i] == '+':
32 i++
33 case s[i] == '-':
34 neg = true
35 i++
38 // digits
39 b := new(decimal)
40 sawdot := false
41 sawdigits := false
42 for ; i < len(s); i++ {
43 switch {
44 case s[i] == '.':
45 if sawdot {
46 return
48 sawdot = true
49 b.dp = b.nd
50 continue
52 case '0' <= s[i] && s[i] <= '9':
53 sawdigits = true
54 if s[i] == '0' && b.nd == 0 { // ignore leading zeros
55 b.dp--
56 continue
58 b.d[b.nd] = s[i]
59 b.nd++
60 continue
62 break
64 if !sawdigits {
65 return
67 if !sawdot {
68 b.dp = b.nd
71 // optional exponent moves decimal point.
72 // if we read a very large, very long number,
73 // just be sure to move the decimal point by
74 // a lot (say, 100000). it doesn't matter if it's
75 // not the exact number.
76 if i < len(s) && s[i] == 'e' {
77 i++
78 if i >= len(s) {
79 return
81 esign := 1
82 if s[i] == '+' {
83 i++
84 } else if s[i] == '-' {
85 i++
86 esign = -1
88 if i >= len(s) || s[i] < '0' || s[i] > '9' {
89 return
91 e := 0
92 for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
93 if e < 10000 {
94 e = e*10 + int(s[i]) - '0'
97 b.dp += e * esign
100 if i != len(s) {
101 return
104 d = b
105 ok = true
106 return
109 // decimal power of ten to binary power of two.
110 var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
112 func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uint64, overflow bool) {
113 var exp int
114 var mant uint64
116 // Zero is always a special case.
117 if d.nd == 0 {
118 mant = 0
119 exp = flt.bias
120 goto out
123 // Obvious overflow/underflow.
124 // These bounds are for 64-bit floats.
125 // Will have to change if we want to support 80-bit floats in the future.
126 if d.dp > 310 {
127 goto overflow
129 if d.dp < -330 {
130 // zero
131 mant = 0
132 exp = flt.bias
133 goto out
136 // Scale by powers of two until in range [0.5, 1.0)
137 exp = 0
138 for d.dp > 0 {
139 var n int
140 if d.dp >= len(powtab) {
141 n = 27
142 } else {
143 n = powtab[d.dp]
145 d.Shift(-n)
146 exp += n
148 for d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
149 var n int
150 if -d.dp >= len(powtab) {
151 n = 27
152 } else {
153 n = powtab[-d.dp]
155 d.Shift(n)
156 exp -= n
159 // Our range is [0.5,1) but floating point range is [1,2).
160 exp--
162 // Minimum representable exponent is flt.bias+1.
163 // If the exponent is smaller, move it up and
164 // adjust d accordingly.
165 if exp < flt.bias+1 {
166 n := flt.bias + 1 - exp
167 d.Shift(-n)
168 exp += n
171 if exp-flt.bias >= 1<<flt.expbits-1 {
172 goto overflow
175 // Extract 1+flt.mantbits bits.
176 mant = d.Shift(int(1 + flt.mantbits)).RoundedInteger()
178 // Rounding might have added a bit; shift down.
179 if mant == 2<<flt.mantbits {
180 mant >>= 1
181 exp++
182 if exp-flt.bias >= 1<<flt.expbits-1 {
183 goto overflow
187 // Denormalized?
188 if mant&(1<<flt.mantbits) == 0 {
189 exp = flt.bias
191 goto out
193 overflow:
194 // ±Inf
195 mant = 0
196 exp = 1<<flt.expbits - 1 + flt.bias
197 overflow = true
199 out:
200 // Assemble bits.
201 bits := mant & (uint64(1)<<flt.mantbits - 1)
202 bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits
203 if neg {
204 bits |= 1 << flt.mantbits << flt.expbits
206 return bits, overflow
209 // Compute exact floating-point integer from d's digits.
210 // Caller is responsible for avoiding overflow.
211 func decimalAtof64Int(neg bool, d *decimal) float64 {
212 f := float64(0)
213 for i := 0; i < d.nd; i++ {
214 f = f*10 + float64(d.d[i]-'0')
216 if neg {
217 f *= -1 // BUG work around 6g f = -f.
219 return f
222 func decimalAtof32Int(neg bool, d *decimal) float32 {
223 f := float32(0)
224 for i := 0; i < d.nd; i++ {
225 f = f*10 + float32(d.d[i]-'0')
227 if neg {
228 f *= -1 // BUG work around 6g f = -f.
230 return f
233 // Exact powers of 10.
234 var float64pow10 = []float64{
235 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
236 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
237 1e20, 1e21, 1e22,
239 var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
241 // If possible to convert decimal d to 64-bit float f exactly,
242 // entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
243 // Three common cases:
244 // value is exact integer
245 // value is exact integer * exact power of ten
246 // value is exact integer / exact power of ten
247 // These all produce potentially inexact but correctly rounded answers.
248 func decimalAtof64(neg bool, d *decimal, trunc bool) (f float64, ok bool) {
249 // Exact integers are <= 10^15.
250 // Exact powers of ten are <= 10^22.
251 if d.nd > 15 {
252 return
254 switch {
255 case d.dp == d.nd: // int
256 f := decimalAtof64Int(neg, d)
257 return f, true
259 case d.dp > d.nd && d.dp <= 15+22: // int * 10^k
260 f := decimalAtof64Int(neg, d)
261 k := d.dp - d.nd
262 // If exponent is big but number of digits is not,
263 // can move a few zeros into the integer part.
264 if k > 22 {
265 f *= float64pow10[k-22]
266 k = 22
268 return f * float64pow10[k], true
270 case d.dp < d.nd && d.nd-d.dp <= 22: // int / 10^k
271 f := decimalAtof64Int(neg, d)
272 return f / float64pow10[d.nd-d.dp], true
274 return
277 // If possible to convert decimal d to 32-bit float f exactly,
278 // entirely in floating-point math, do so, avoiding the machinery above.
279 func decimalAtof32(neg bool, d *decimal, trunc bool) (f float32, ok bool) {
280 // Exact integers are <= 10^7.
281 // Exact powers of ten are <= 10^10.
282 if d.nd > 7 {
283 return
285 switch {
286 case d.dp == d.nd: // int
287 f := decimalAtof32Int(neg, d)
288 return f, true
290 case d.dp > d.nd && d.dp <= 7+10: // int * 10^k
291 f := decimalAtof32Int(neg, d)
292 k := d.dp - d.nd
293 // If exponent is big but number of digits is not,
294 // can move a few zeros into the integer part.
295 if k > 10 {
296 f *= float32pow10[k-10]
297 k = 10
299 return f * float32pow10[k], true
301 case d.dp < d.nd && d.nd-d.dp <= 10: // int / 10^k
302 f := decimalAtof32Int(neg, d)
303 return f / float32pow10[d.nd-d.dp], true
305 return
308 // Atof32 converts the string s to a 32-bit floating-point number.
310 // If s is well-formed and near a valid floating point number,
311 // Atof32 returns the nearest floating point number rounded
312 // using IEEE754 unbiased rounding.
314 // The errors that Atof32 returns have concrete type *NumError
315 // and include err.Num = s.
317 // If s is not syntactically well-formed, Atof32 returns err.Error = os.EINVAL.
319 // If s is syntactically well-formed but is more than 1/2 ULP
320 // away from the largest floating point number of the given size,
321 // Atof32 returns f = ±Inf, err.Error = os.ERANGE.
322 func Atof32(s string) (f float32, err os.Error) {
323 neg, d, trunc, ok := stringToDecimal(s)
324 if !ok {
325 return 0, &NumError{s, os.EINVAL}
327 if optimize {
328 if f, ok := decimalAtof32(neg, d, trunc); ok {
329 return f, nil
332 b, ovf := decimalToFloatBits(neg, d, trunc, &float32info)
333 f = math.Float32frombits(uint32(b))
334 if ovf {
335 err = &NumError{s, os.ERANGE}
337 return f, err
340 // Atof64 converts the string s to a 64-bit floating-point number.
341 // Except for the type of its result, its definition is the same as that
342 // of Atof32.
343 func Atof64(s string) (f float64, err os.Error) {
344 neg, d, trunc, ok := stringToDecimal(s)
345 if !ok {
346 return 0, &NumError{s, os.EINVAL}
348 if optimize {
349 if f, ok := decimalAtof64(neg, d, trunc); ok {
350 return f, nil
353 b, ovf := decimalToFloatBits(neg, d, trunc, &float64info)
354 f = math.Float64frombits(b)
355 if ovf {
356 err = &NumError{s, os.ERANGE}
358 return f, err
361 // Atof is like Atof32 or Atof64, depending on the size of float.
362 func Atof(s string) (f float, err os.Error) {
363 if FloatSize == 32 {
364 f1, err1 := Atof32(s)
365 return float(f1), err1
367 f1, err1 := Atof64(s)
368 return float(f1), err1
372 // AtofN converts the string s to a 64-bit floating-point number,
373 // but it rounds the result assuming that it will be stored in a value
374 // of n bits (32 or 64).
375 func AtofN(s string, n int) (f float64, err os.Error) {
376 if n == 32 {
377 f1, err1 := Atof32(s)
378 return float64(f1), err1
380 f1, err1 := Atof64(s)
381 return f1, err1