Source file test/fixedbugs/bug120.go

     1  // run
     2  
     3  // Copyright 2009 The Go Authors. All rights reserved.
     4  // Use of this source code is governed by a BSD-style
     5  // license that can be found in the LICENSE file.
     6  
     7  package main
     8  
     9  import "os"
    10  import "strconv"
    11  
    12  type Test struct {
    13  	f   float64
    14  	in  string
    15  	out string
    16  }
    17  
    18  var tests = []Test{
    19  	Test{123.5, "123.5", "123.5"},
    20  	Test{456.7, "456.7", "456.7"},
    21  	Test{1e23 + 8.5e6, "1e23+8.5e6", "1.0000000000000001e+23"},
    22  	Test{100000000000000008388608, "100000000000000008388608", "1.0000000000000001e+23"},
    23  	Test{1e23 + 8388609, "1e23+8388609", "1.0000000000000001e+23"},
    24  
    25  	// "x" = the floating point value from converting the string x.
    26  	// These are exactly representable in 64-bit floating point:
    27  	//	1e23-8388608
    28  	//	1e23+8388608
    29  	// The former has an even mantissa, so "1e23" rounds to 1e23-8388608.
    30  	// If "1e23+8388608" is implemented as "1e23" + "8388608",
    31  	// that ends up computing 1e23-8388608 + 8388608 = 1e23,
    32  	// which rounds back to 1e23-8388608.
    33  	// The correct answer, of course, would be "1e23+8388608" = 1e23+8388608.
    34  	// This is not going to be correct until 6g has multiprecision floating point.
    35  	// A simpler case is "1e23+1", which should also round to 1e23+8388608.
    36  	Test{1e23 + 8.388608e6, "1e23+8.388608e6", "1.0000000000000001e+23"},
    37  	Test{1e23 + 1, "1e23+1", "1.0000000000000001e+23"},
    38  }
    39  
    40  func main() {
    41  	ok := true
    42  	for i := 0; i < len(tests); i++ {
    43  		t := tests[i]
    44  		v := strconv.FormatFloat(t.f, 'g', -1, 64)
    45  		if v != t.out {
    46  			println("Bad float64 const:", t.in, "want", t.out, "got", v)
    47  			x, err := strconv.ParseFloat(t.out, 64)
    48  			if err != nil {
    49  				println("bug120: strconv.Atof64", t.out)
    50  				panic("fail")
    51  			}
    52  			println("\twant exact:", strconv.FormatFloat(x, 'g', 1000, 64))
    53  			println("\tgot exact: ", strconv.FormatFloat(t.f, 'g', 1000, 64))
    54  			ok = false
    55  		}
    56  	}
    57  	if !ok {
    58  		os.Exit(1)
    59  	}
    60  }
    61  

View as plain text