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.
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.
20
var optimize = true // can change for testing
22
func equalIgnoreCase(s1, s2 string) bool {
23
if len(s1) != len(s2) {
26
for i := 0; i < len(s1); i++ {
28
if 'A' <= c1 && c1 <= 'Z' {
32
if 'A' <= c2 && c2 <= 'Z' {
42
func special(s string) (f float64, ok bool) {
44
case equalIgnoreCase(s, "nan"):
45
return math.NaN(), true
46
case equalIgnoreCase(s, "-inf"):
47
return math.Inf(-1), true
48
case equalIgnoreCase(s, "+inf"):
49
return math.Inf(1), true
50
case equalIgnoreCase(s, "inf"):
51
return math.Inf(1), true
56
// TODO(rsc): Better truncation handling.
57
func stringToDecimal(s string) (neg bool, d *decimal, trunc bool, ok bool) {
76
for ; i < len(s); i++ {
86
case '0' <= s[i] && s[i] <= '9':
88
if s[i] == '0' && b.nd == 0 { // ignore leading zeros
105
// optional exponent moves decimal point.
106
// if we read a very large, very long number,
107
// just be sure to move the decimal point by
108
// a lot (say, 100000). it doesn't matter if it's
109
// not the exact number.
110
if i < len(s) && (s[i] == 'e' || s[i] == 'E') {
118
} else if s[i] == '-' {
122
if i >= len(s) || s[i] < '0' || s[i] > '9' {
126
for ; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
128
e = e*10 + int(s[i]) - '0'
143
// decimal power of ten to binary power of two.
144
var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
146
func decimalToFloatBits(neg bool, d *decimal, trunc bool, flt *floatInfo) (b uint64, overflow bool) {
150
// Zero is always a special case.
157
// Obvious overflow/underflow.
158
// These bounds are for 64-bit floats.
159
// Will have to change if we want to support 80-bit floats in the future.
170
// Scale by powers of two until in range [0.5, 1.0)
174
if d.dp >= len(powtab) {
182
for d.dp < 0 || d.dp == 0 && d.d[0] < '5' {
184
if -d.dp >= len(powtab) {
193
// Our range is [0.5,1) but floating point range is [1,2).
196
// Minimum representable exponent is flt.bias+1.
197
// If the exponent is smaller, move it up and
198
// adjust d accordingly.
199
if exp < flt.bias+1 {
200
n := flt.bias + 1 - exp
205
if exp-flt.bias >= 1<<flt.expbits-1 {
209
// Extract 1+flt.mantbits bits.
210
mant = d.Shift(int(1 + flt.mantbits)).RoundedInteger()
212
// Rounding might have added a bit; shift down.
213
if mant == 2<<flt.mantbits {
216
if exp-flt.bias >= 1<<flt.expbits-1 {
222
if mant&(1<<flt.mantbits) == 0 {
230
exp = 1<<flt.expbits - 1 + flt.bias
235
bits := mant & (uint64(1)<<flt.mantbits - 1)
236
bits |= uint64((exp-flt.bias)&(1<<flt.expbits-1)) << flt.mantbits
238
bits |= 1 << flt.mantbits << flt.expbits
240
return bits, overflow
243
// Compute exact floating-point integer from d's digits.
244
// Caller is responsible for avoiding overflow.
245
func decimalAtof64Int(neg bool, d *decimal) float64 {
247
for i := 0; i < d.nd; i++ {
248
f = f*10 + float64(d.d[i]-'0')
251
f *= -1 // BUG work around 6g f = -f.
256
func decimalAtof32Int(neg bool, d *decimal) float32 {
258
for i := 0; i < d.nd; i++ {
259
f = f*10 + float32(d.d[i]-'0')
262
f *= -1 // BUG work around 6g f = -f.
267
// Exact powers of 10.
268
var float64pow10 = []float64{
269
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
270
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
273
var float32pow10 = []float32{1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10}
275
// If possible to convert decimal d to 64-bit float f exactly,
276
// entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
277
// Three common cases:
278
// value is exact integer
279
// value is exact integer * exact power of ten
280
// value is exact integer / exact power of ten
281
// These all produce potentially inexact but correctly rounded answers.
282
func decimalAtof64(neg bool, d *decimal, trunc bool) (f float64, ok bool) {
283
// Exact integers are <= 10^15.
284
// Exact powers of ten are <= 10^22.
289
case d.dp == d.nd: // int
290
f := decimalAtof64Int(neg, d)
293
case d.dp > d.nd && d.dp <= 15+22: // int * 10^k
294
f := decimalAtof64Int(neg, d)
296
// If exponent is big but number of digits is not,
297
// can move a few zeros into the integer part.
299
f *= float64pow10[k-22]
302
return f * float64pow10[k], true
304
case d.dp < d.nd && d.nd-d.dp <= 22: // int / 10^k
305
f := decimalAtof64Int(neg, d)
306
return f / float64pow10[d.nd-d.dp], true
311
// If possible to convert decimal d to 32-bit float f exactly,
312
// entirely in floating-point math, do so, avoiding the machinery above.
313
func decimalAtof32(neg bool, d *decimal, trunc bool) (f float32, ok bool) {
314
// Exact integers are <= 10^7.
315
// Exact powers of ten are <= 10^10.
320
case d.dp == d.nd: // int
321
f := decimalAtof32Int(neg, d)
324
case d.dp > d.nd && d.dp <= 7+10: // int * 10^k
325
f := decimalAtof32Int(neg, d)
327
// If exponent is big but number of digits is not,
328
// can move a few zeros into the integer part.
330
f *= float32pow10[k-10]
333
return f * float32pow10[k], true
335
case d.dp < d.nd && d.nd-d.dp <= 10: // int / 10^k
336
f := decimalAtof32Int(neg, d)
337
return f / float32pow10[d.nd-d.dp], true
342
// Atof32 converts the string s to a 32-bit floating-point number.
344
// If s is well-formed and near a valid floating point number,
345
// Atof32 returns the nearest floating point number rounded
346
// using IEEE754 unbiased rounding.
348
// The errors that Atof32 returns have concrete type *NumError
349
// and include err.Num = s.
351
// If s is not syntactically well-formed, Atof32 returns err.Error = os.EINVAL.
353
// If s is syntactically well-formed but is more than 1/2 ULP
354
// away from the largest floating point number of the given size,
355
// Atof32 returns f = ±Inf, err.Error = os.ERANGE.
356
func Atof32(s string) (f float32, err os.Error) {
357
if val, ok := special(s); ok {
358
return float32(val), nil
361
neg, d, trunc, ok := stringToDecimal(s)
363
return 0, &NumError{s, os.EINVAL}
366
if f, ok := decimalAtof32(neg, d, trunc); ok {
370
b, ovf := decimalToFloatBits(neg, d, trunc, &float32info)
371
f = math.Float32frombits(uint32(b))
373
err = &NumError{s, os.ERANGE}
378
// Atof64 converts the string s to a 64-bit floating-point number.
379
// Except for the type of its result, its definition is the same as that
381
func Atof64(s string) (f float64, err os.Error) {
382
if val, ok := special(s); ok {
386
neg, d, trunc, ok := stringToDecimal(s)
388
return 0, &NumError{s, os.EINVAL}
391
if f, ok := decimalAtof64(neg, d, trunc); ok {
395
b, ovf := decimalToFloatBits(neg, d, trunc, &float64info)
396
f = math.Float64frombits(b)
398
err = &NumError{s, os.ERANGE}
403
// AtofN converts the string s to a 64-bit floating-point number,
404
// but it rounds the result assuming that it will be stored in a value
405
// of n bits (32 or 64).
406
func AtofN(s string, n int) (f float64, err os.Error) {
408
f1, err1 := Atof32(s)
409
return float64(f1), err1
411
f1, err1 := Atof64(s)