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.
16 func pow2(i
int) float64 {
25 return pow2(i
/2) * pow2(i
-i
/2)
28 // Wrapper around strconv.ParseFloat(x, 64). Handles dddddp+ddd (binary exponent)
29 // itself, passes the rest on to strconv.ParseFloat.
30 func myatof64(s
string) (f
float64, ok
bool) {
31 if mant
, exp
, ok
:= strings
.Cut(s
, "p"); ok
{
32 n
, err
:= strconv
.ParseInt(mant
, 10, 64)
36 e
, err1
:= strconv
.Atoi(exp
)
42 // We expect that v*pow2(e) fits in a float64,
43 // but pow2(e) by itself may not. Be careful.
62 return v
* pow2(e
), true
64 f1
, err
:= strconv
.ParseFloat(s
, 64)
71 // Wrapper around strconv.ParseFloat(x, 32). Handles dddddp+ddd (binary exponent)
72 // itself, passes the rest on to strconv.ParseFloat.
73 func myatof32(s
string) (f
float32, ok
bool) {
74 if mant
, exp
, ok
:= strings
.Cut(s
, "p"); ok
{
75 n
, err
:= strconv
.Atoi(mant
)
77 println("bad n", mant
)
80 e
, err1
:= strconv
.Atoi(exp
)
85 return float32(float64(n
) * pow2(e
)), true
87 f64
, err1
:= strconv
.ParseFloat(s
, 32)
95 func TestFp(t
*testing
.T
) {
96 f
, err
:= os
.Open("testdata/testfp.txt")
98 t
.Fatal("testfp: open testdata/testfp.txt:", err
)
102 s
:= bufio
.NewScanner(f
)
104 for lineno
:= 1; s
.Scan(); lineno
++ {
106 if len(line
) == 0 || line
[0] == '#' {
109 a
:= strings
.Split(line
, " ")
111 t
.Error("testdata/testfp.txt:", lineno
, ": wrong field count")
119 v
, ok
= myatof64(a
[2])
121 t
.Error("testdata/testfp.txt:", lineno
, ": cannot atof64 ", a
[2])
124 s
= fmt
.Sprintf(a
[1], v
)
126 v1
, ok
:= myatof32(a
[2])
128 t
.Error("testdata/testfp.txt:", lineno
, ": cannot atof32 ", a
[2])
131 s
= fmt
.Sprintf(a
[1], v1
)
135 t
.Error("testdata/testfp.txt:", lineno
, ": ", a
[0], " ", a
[1], " ", a
[2], " (", v
, ") ",
136 "want ", a
[3], " got ", s
)
140 t
.Fatal("testfp: read testdata/testfp.txt: ", s
.Err())