OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [strconv/] [atof.go] - Blame information for rev 861

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// 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.
4
 
5
// Package strconv implements conversions to and from string representations
6
// of basic data types.
7
package strconv
8
 
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.
14
 
15
import "math"
16
 
17
var optimize = true // can change for testing
18
 
19
func equalIgnoreCase(s1, s2 string) bool {
20
        if len(s1) != len(s2) {
21
                return false
22
        }
23
        for i := 0; i < len(s1); i++ {
24
                c1 := s1[i]
25
                if 'A' <= c1 && c1 <= 'Z' {
26
                        c1 += 'a' - 'A'
27
                }
28
                c2 := s2[i]
29
                if 'A' <= c2 && c2 <= 'Z' {
30
                        c2 += 'a' - 'A'
31
                }
32
                if c1 != c2 {
33
                        return false
34
                }
35
        }
36
        return true
37
}
38
 
39
func special(s string) (f float64, ok bool) {
40
        switch {
41
        case equalIgnoreCase(s, "nan"):
42
                return math.NaN(), true
43
        case equalIgnoreCase(s, "-inf"),
44
                equalIgnoreCase(s, "-infinity"):
45
                return math.Inf(-1), true
46
        case equalIgnoreCase(s, "+inf"),
47
                equalIgnoreCase(s, "+infinity"),
48
                equalIgnoreCase(s, "inf"),
49
                equalIgnoreCase(s, "infinity"):
50
                return math.Inf(1), true
51
        }
52
        return
53
}
54
 
55
// TODO(rsc): Better truncation handling.
56
func (b *decimal) set(s string) (ok bool) {
57
        i := 0
58
        b.neg = false
59
 
60
        // optional sign
61
        if i >= len(s) {
62
                return
63
        }
64
        switch {
65
        case s[i] == '+':
66
                i++
67
        case s[i] == '-':
68
                b.neg = true
69
                i++
70
        }
71
 
72
        // digits
73
        sawdot := false
74
        sawdigits := false
75
        for ; i < len(s); i++ {
76
                switch {
77
                case s[i] == '.':
78
                        if sawdot {
79
                                return
80
                        }
81
                        sawdot = true
82
                        b.dp = b.nd
83
                        continue
84
 
85
                case '0' <= s[i] && s[i] <= '9':
86
                        sawdigits = true
87
                        if s[i] == '0' && b.nd == 0 { // ignore leading zeros
88
                                b.dp--
89
                                continue
90
                        }
91
                        b.d[b.nd] = s[i]
92
                        b.nd++
93
                        continue
94
                }
95
                break
96
        }
97
        if !sawdigits {
98
                return
99
        }
100
        if !sawdot {
101
                b.dp = b.nd
102
        }
103
 
104
        // optional exponent moves decimal point.
105
        // if we read a very large, very long number,
106
        // just be sure to move the decimal point by
107
        // a lot (say, 100000).  it doesn't matter if it's
108
        // not the exact number.
109
        if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
110
                i++
111
                if i >= len(s) {
112
                        return
113
                }
114
                esign := 1
115
                if s[i] == '+' {
116
                        i++
117
                } else if s[i] == '-' {
118
                        i++
119
                        esign = -1
120
                }
121
                if i >= len(s) || s[i] < '0' || s[i] > '9' {
122
                        return
123
                }
124
                e := 0
125
                for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
126
                        if e < 10000 {
127
                                e = e*10 + int(s[i]) - '0'
128
                        }
129
                }
130
                b.dp += e * esign
131
        }
132
 
133
        if i != len(s) {
134
                return
135
        }
136
 
137
        ok = true
138
        return
139
}
140
 
141
// decimal power of ten to binary power of two.
142
var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
143
 
144
func (d *decimal) floatBits(flt *floatInfo) (b uint64, overflow bool) {
145
        var exp int
146
        var mant uint64
147
 
148
        // Zero is always a special case.
149
        if d.nd == 0 {
150
                mant = 0
151
                exp = flt.bias
152
                goto out
153
        }
154
 
155
        // Obvious overflow/underflow.
156
        // These bounds are for 64-bit floats.
157
        // Will have to change if we want to support 80-bit floats in the future.
158
        if d.dp > 310 {
159
                goto overflow
160
        }
161
        if d.dp < -330 {
162
                // zero
163
                mant = 0
164
                exp = flt.bias
165
                goto out
166
        }
167
 
168
        // Scale by powers of two until in range [0.5, 1.0)
169
        exp = 0
170
        for d.dp > 0 {
171
                var n int
172
                if d.dp >= len(powtab) {
173
                        n = 27
174
                } else {
175
                        n = powtab[d.dp]
176
                }
177
                d.Shift(-n)
178
                exp += n
179
        }
180
        for d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
181
                var n int
182
                if -d.dp >= len(powtab) {
183
                        n = 27
184
                } else {
185
                        n = powtab[-d.dp]
186
                }
187
                d.Shift(n)
188
                exp -= n
189
        }
190
 
191
        // Our range is [0.5,1) but floating point range is [1,2).
192
        exp--
193
 
194
        // Minimum representable exponent is flt.bias+1.
195
        // If the exponent is smaller, move it up and
196
        // adjust d accordingly.
197
        if exp < flt.bias+1 {
198
                n := flt.bias + 1 - exp
199
                d.Shift(-n)
200
                exp += n
201
        }
202
 
203
        if exp-flt.bias >= 1<
204
                goto overflow
205
        }
206
 
207
        // Extract 1+flt.mantbits bits.
208
        d.Shift(int(1 + flt.mantbits))
209
        mant = d.RoundedInteger()
210
 
211
        // Rounding might have added a bit; shift down.
212
        if mant == 2<
213
                mant >>= 1
214
                exp++
215
                if exp-flt.bias >= 1<
216
                        goto overflow
217
                }
218
        }
219
 
220
        // Denormalized?
221
        if mant&(1<
222
                exp = flt.bias
223
        }
224
        goto out
225
 
226
overflow:
227
        // ±Inf
228
        mant = 0
229
        exp = 1<
230
        overflow = true
231
 
232
out:
233
        // Assemble bits.
234
        bits := mant & (uint64(1)<
235
        bits |= uint64((exp-flt.bias)&(1<
236
        if d.neg {
237
                bits |= 1 << flt.mantbits << flt.expbits
238
        }
239
        return bits, overflow
240
}
241
 
242
// Compute exact floating-point integer from d's digits.
243
// Caller is responsible for avoiding overflow.
244
func (d *decimal) atof64int() float64 {
245
        f := 0.0
246
        for i := 0; i < d.nd; i++ {
247
                f = f*10 + float64(d.d[i]-'0')
248
        }
249
        if d.neg {
250
                f = -f
251
        }
252
        return f
253
}
254
 
255
func (d *decimal) atof32int() float32 {
256
        f := float32(0)
257
        for i := 0; i < d.nd; i++ {
258
                f = f*10 + float32(d.d[i]-'0')
259
        }
260
        if d.neg {
261
                f = -f
262
        }
263
        return f
264
}
265
 
266
// Reads a uint64 decimal mantissa, which might be truncated.
267
func (d *decimal) atou64() (mant uint64, digits int) {
268
        const uint64digits = 19
269
        for i, c := range d.d[:d.nd] {
270
                if i == uint64digits {
271
                        return mant, i
272
                }
273
                mant = 10*mant + uint64(c-'0')
274
        }
275
        return mant, d.nd
276
}
277
 
278
// Exact powers of 10.
279
var float64pow10 = []float64{
280
        1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
281
        1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
282
        1e20, 1e21, 1e22,
283
}
284
var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
285
 
286
// If possible to convert decimal d to 64-bit float f exactly,
287
// entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
288
// Three common cases:
289
//      value is exact integer
290
//      value is exact integer * exact power of ten
291
//      value is exact integer / exact power of ten
292
// These all produce potentially inexact but correctly rounded answers.
293
func (d *decimal) atof64() (f float64, ok bool) {
294
        // Exact integers are <= 10^15.
295
        // Exact powers of ten are <= 10^22.
296
        if d.nd > 15 {
297
                return
298
        }
299
        switch {
300
        case d.dp == d.nd: // int
301
                f := d.atof64int()
302
                return f, true
303
 
304
        case d.dp > d.nd && d.dp <= 15+22: // int * 10^k
305
                f := d.atof64int()
306
                k := d.dp - d.nd
307
                // If exponent is big but number of digits is not,
308
                // can move a few zeros into the integer part.
309
                if k > 22 {
310
                        f *= float64pow10[k-22]
311
                        k = 22
312
                }
313
                return f * float64pow10[k], true
314
 
315
        case d.dp < d.nd && d.nd-d.dp <= 22: // int / 10^k
316
                f := d.atof64int()
317
                return f / float64pow10[d.nd-d.dp], true
318
        }
319
        return
320
}
321
 
322
// If possible to convert decimal d to 32-bit float f exactly,
323
// entirely in floating-point math, do so, avoiding the machinery above.
324
func (d *decimal) atof32() (f float32, ok bool) {
325
        // Exact integers are <= 10^7.
326
        // Exact powers of ten are <= 10^10.
327
        if d.nd > 7 {
328
                return
329
        }
330
        switch {
331
        case d.dp == d.nd: // int
332
                f := d.atof32int()
333
                return f, true
334
 
335
        case d.dp > d.nd && d.dp <= 7+10: // int * 10^k
336
                f := d.atof32int()
337
                k := d.dp - d.nd
338
                // If exponent is big but number of digits is not,
339
                // can move a few zeros into the integer part.
340
                if k > 10 {
341
                        f *= float32pow10[k-10]
342
                        k = 10
343
                }
344
                return f * float32pow10[k], true
345
 
346
        case d.dp < d.nd && d.nd-d.dp <= 10: // int / 10^k
347
                f := d.atof32int()
348
                return f / float32pow10[d.nd-d.dp], true
349
        }
350
        return
351
}
352
 
353
const fnParseFloat = "ParseFloat"
354
 
355
func atof32(s string) (f float32, err error) {
356
        if val, ok := special(s); ok {
357
                return float32(val), nil
358
        }
359
 
360
        var d decimal
361
        if !d.set(s) {
362
                return 0, syntaxError(fnParseFloat, s)
363
        }
364
        if optimize {
365
                if f, ok := d.atof32(); ok {
366
                        return f, nil
367
                }
368
        }
369
        b, ovf := d.floatBits(&float32info)
370
        f = math.Float32frombits(uint32(b))
371
        if ovf {
372
                err = rangeError(fnParseFloat, s)
373
        }
374
        return f, err
375
}
376
 
377
func atof64(s string) (f float64, err error) {
378
        if val, ok := special(s); ok {
379
                return val, nil
380
        }
381
 
382
        var d decimal
383
        if !d.set(s) {
384
                return 0, syntaxError(fnParseFloat, s)
385
        }
386
        if optimize {
387
                if f, ok := d.atof64(); ok {
388
                        return f, nil
389
                }
390
 
391
                // Try another fast path.
392
                ext := new(extFloat)
393
                if ok := ext.AssignDecimal(&d); ok {
394
                        b, ovf := ext.floatBits()
395
                        f = math.Float64frombits(b)
396
                        if ovf {
397
                                err = rangeError(fnParseFloat, s)
398
                        }
399
                        return f, err
400
                }
401
        }
402
        b, ovf := d.floatBits(&float64info)
403
        f = math.Float64frombits(b)
404
        if ovf {
405
                err = rangeError(fnParseFloat, s)
406
        }
407
        return f, err
408
}
409
 
410
// ParseFloat converts the string s to a floating-point number
411
// with the precision specified by bitSize: 32 for float32, or 64 for float64.
412
// When bitSize=32, the result still has type float64, but it will be
413
// convertible to float32 without changing its value.
414
//
415
// If s is well-formed and near a valid floating point number,
416
// ParseFloat returns the nearest floating point number rounded
417
// using IEEE754 unbiased rounding.
418
//
419
// The errors that ParseFloat returns have concrete type *NumError
420
// and include err.Num = s.
421
//
422
// If s is not syntactically well-formed, ParseFloat returns err.Error = ErrSyntax.
423
//
424
// If s is syntactically well-formed but is more than 1/2 ULP
425
// away from the largest floating point number of the given size,
426
// ParseFloat returns f = ±Inf, err.Error = ErrRange.
427
func ParseFloat(s string, bitSize int) (f float64, err error) {
428
        if bitSize == 32 {
429
                f1, err1 := atof32(s)
430
                return float64(f1), err1
431
        }
432
        f1, err1 := atof64(s)
433
        return f1, err1
434
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.