...
Run Format

Source file src/math/big/ratconv_test.go

Documentation: math/big

     1  // Copyright 2015 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 big
     6  
     7  import (
     8  	"bytes"
     9  	"fmt"
    10  	"math"
    11  	"strconv"
    12  	"strings"
    13  	"testing"
    14  )
    15  
    16  type StringTest struct {
    17  	in, out string
    18  	ok      bool
    19  }
    20  
    21  var setStringTests = []StringTest{
    22  	{"0", "0", true},
    23  	{"-0", "0", true},
    24  	{"1", "1", true},
    25  	{"-1", "-1", true},
    26  	{"1.", "1", true},
    27  	{"1e0", "1", true},
    28  	{"1.e1", "10", true},
    29  	{in: "1e"},
    30  	{in: "1.e"},
    31  	{in: "1e+14e-5"},
    32  	{in: "1e4.5"},
    33  	{in: "r"},
    34  	{in: "a/b"},
    35  	{in: "a.b"},
    36  	{"-0.1", "-1/10", true},
    37  	{"-.1", "-1/10", true},
    38  	{"2/4", "1/2", true},
    39  	{".25", "1/4", true},
    40  	{"-1/5", "-1/5", true},
    41  	{"8129567.7690E14", "812956776900000000000", true},
    42  	{"78189e+4", "781890000", true},
    43  	{"553019.8935e+8", "55301989350000", true},
    44  	{"98765432109876543210987654321e-10", "98765432109876543210987654321/10000000000", true},
    45  	{"9877861857500000E-7", "3951144743/4", true},
    46  	{"2169378.417e-3", "2169378417/1000000", true},
    47  	{"884243222337379604041632732738665534", "884243222337379604041632732738665534", true},
    48  	{"53/70893980658822810696", "53/70893980658822810696", true},
    49  	{"106/141787961317645621392", "53/70893980658822810696", true},
    50  	{"204211327800791583.81095", "4084226556015831676219/20000", true},
    51  	{"0e9999999999", "0", true}, // issue #16176
    52  	{in: "1/0"},
    53  	{in: "4/3/2"}, // issue 17001
    54  	{in: "4/3/"},
    55  	{in: "4/3."},
    56  	{in: "4/"},
    57  }
    58  
    59  // These are not supported by fmt.Fscanf.
    60  var setStringTests2 = []StringTest{
    61  	{"0x10", "16", true},
    62  	{"-010/1", "-8", true}, // TODO(gri) should we even permit octal here?
    63  	{"-010.", "-10", true},
    64  	{"0x10/0x20", "1/2", true},
    65  	{"0b1000/3", "8/3", true},
    66  	{in: "4/3x"},
    67  	// TODO(gri) add more tests
    68  }
    69  
    70  func TestRatSetString(t *testing.T) {
    71  	var tests []StringTest
    72  	tests = append(tests, setStringTests...)
    73  	tests = append(tests, setStringTests2...)
    74  
    75  	for i, test := range tests {
    76  		x, ok := new(Rat).SetString(test.in)
    77  
    78  		if ok {
    79  			if !test.ok {
    80  				t.Errorf("#%d SetString(%q) expected failure", i, test.in)
    81  			} else if x.RatString() != test.out {
    82  				t.Errorf("#%d SetString(%q) got %s want %s", i, test.in, x.RatString(), test.out)
    83  			}
    84  		} else if x != nil {
    85  			t.Errorf("#%d SetString(%q) got %p want nil", i, test.in, x)
    86  		}
    87  	}
    88  }
    89  
    90  func TestRatScan(t *testing.T) {
    91  	var buf bytes.Buffer
    92  	for i, test := range setStringTests {
    93  		x := new(Rat)
    94  		buf.Reset()
    95  		buf.WriteString(test.in)
    96  
    97  		_, err := fmt.Fscanf(&buf, "%v", x)
    98  		if err == nil != test.ok {
    99  			if test.ok {
   100  				t.Errorf("#%d (%s) error: %s", i, test.in, err)
   101  			} else {
   102  				t.Errorf("#%d (%s) expected error", i, test.in)
   103  			}
   104  			continue
   105  		}
   106  		if err == nil && x.RatString() != test.out {
   107  			t.Errorf("#%d got %s want %s", i, x.RatString(), test.out)
   108  		}
   109  	}
   110  }
   111  
   112  var floatStringTests = []struct {
   113  	in   string
   114  	prec int
   115  	out  string
   116  }{
   117  	{"0", 0, "0"},
   118  	{"0", 4, "0.0000"},
   119  	{"1", 0, "1"},
   120  	{"1", 2, "1.00"},
   121  	{"-1", 0, "-1"},
   122  	{"0.05", 1, "0.1"},
   123  	{"-0.05", 1, "-0.1"},
   124  	{".25", 2, "0.25"},
   125  	{".25", 1, "0.3"},
   126  	{".25", 3, "0.250"},
   127  	{"-1/3", 3, "-0.333"},
   128  	{"-2/3", 4, "-0.6667"},
   129  	{"0.96", 1, "1.0"},
   130  	{"0.999", 2, "1.00"},
   131  	{"0.9", 0, "1"},
   132  	{".25", -1, "0"},
   133  	{".55", -1, "1"},
   134  }
   135  
   136  func TestFloatString(t *testing.T) {
   137  	for i, test := range floatStringTests {
   138  		x, _ := new(Rat).SetString(test.in)
   139  
   140  		if x.FloatString(test.prec) != test.out {
   141  			t.Errorf("#%d got %s want %s", i, x.FloatString(test.prec), test.out)
   142  		}
   143  	}
   144  }
   145  
   146  // Test inputs to Rat.SetString. The prefix "long:" causes the test
   147  // to be skipped except in -long mode.  (The threshold is about 500us.)
   148  var float64inputs = []string{
   149  	// Constants plundered from strconv/testfp.txt.
   150  
   151  	// Table 1: Stress Inputs for Conversion to 53-bit Binary, < 1/2 ULP
   152  	"5e+125",
   153  	"69e+267",
   154  	"999e-026",
   155  	"7861e-034",
   156  	"75569e-254",
   157  	"928609e-261",
   158  	"9210917e+080",
   159  	"84863171e+114",
   160  	"653777767e+273",
   161  	"5232604057e-298",
   162  	"27235667517e-109",
   163  	"653532977297e-123",
   164  	"3142213164987e-294",
   165  	"46202199371337e-072",
   166  	"231010996856685e-073",
   167  	"9324754620109615e+212",
   168  	"78459735791271921e+049",
   169  	"272104041512242479e+200",
   170  	"6802601037806061975e+198",
   171  	"20505426358836677347e-221",
   172  	"836168422905420598437e-234",
   173  	"4891559871276714924261e+222",
   174  
   175  	// Table 2: Stress Inputs for Conversion to 53-bit Binary, > 1/2 ULP
   176  	"9e-265",
   177  	"85e-037",
   178  	"623e+100",
   179  	"3571e+263",
   180  	"81661e+153",
   181  	"920657e-023",
   182  	"4603285e-024",
   183  	"87575437e-309",
   184  	"245540327e+122",
   185  	"6138508175e+120",
   186  	"83356057653e+193",
   187  	"619534293513e+124",
   188  	"2335141086879e+218",
   189  	"36167929443327e-159",
   190  	"609610927149051e-255",
   191  	"3743626360493413e-165",
   192  	"94080055902682397e-242",
   193  	"899810892172646163e+283",
   194  	"7120190517612959703e+120",
   195  	"25188282901709339043e-252",
   196  	"308984926168550152811e-052",
   197  	"6372891218502368041059e+064",
   198  
   199  	// Table 14: Stress Inputs for Conversion to 24-bit Binary, <1/2 ULP
   200  	"5e-20",
   201  	"67e+14",
   202  	"985e+15",
   203  	"7693e-42",
   204  	"55895e-16",
   205  	"996622e-44",
   206  	"7038531e-32",
   207  	"60419369e-46",
   208  	"702990899e-20",
   209  	"6930161142e-48",
   210  	"25933168707e+13",
   211  	"596428896559e+20",
   212  
   213  	// Table 15: Stress Inputs for Conversion to 24-bit Binary, >1/2 ULP
   214  	"3e-23",
   215  	"57e+18",
   216  	"789e-35",
   217  	"2539e-18",
   218  	"76173e+28",
   219  	"887745e-11",
   220  	"5382571e-37",
   221  	"82381273e-35",
   222  	"750486563e-38",
   223  	"3752432815e-39",
   224  	"75224575729e-45",
   225  	"459926601011e+15",
   226  
   227  	// Constants plundered from strconv/atof_test.go.
   228  
   229  	"0",
   230  	"1",
   231  	"+1",
   232  	"1e23",
   233  	"1E23",
   234  	"100000000000000000000000",
   235  	"1e-100",
   236  	"123456700",
   237  	"99999999999999974834176",
   238  	"100000000000000000000001",
   239  	"100000000000000008388608",
   240  	"100000000000000016777215",
   241  	"100000000000000016777216",
   242  	"-1",
   243  	"-0.1",
   244  	"-0", // NB: exception made for this input
   245  	"1e-20",
   246  	"625e-3",
   247  
   248  	// largest float64
   249  	"1.7976931348623157e308",
   250  	"-1.7976931348623157e308",
   251  	// next float64 - too large
   252  	"1.7976931348623159e308",
   253  	"-1.7976931348623159e308",
   254  	// the border is ...158079
   255  	// borderline - okay
   256  	"1.7976931348623158e308",
   257  	"-1.7976931348623158e308",
   258  	// borderline - too large
   259  	"1.797693134862315808e308",
   260  	"-1.797693134862315808e308",
   261  
   262  	// a little too large
   263  	"1e308",
   264  	"2e308",
   265  	"1e309",
   266  
   267  	// way too large
   268  	"1e310",
   269  	"-1e310",
   270  	"1e400",
   271  	"-1e400",
   272  	"long:1e400000",
   273  	"long:-1e400000",
   274  
   275  	// denormalized
   276  	"1e-305",
   277  	"1e-306",
   278  	"1e-307",
   279  	"1e-308",
   280  	"1e-309",
   281  	"1e-310",
   282  	"1e-322",
   283  	// smallest denormal
   284  	"5e-324",
   285  	"4e-324",
   286  	"3e-324",
   287  	// too small
   288  	"2e-324",
   289  	// way too small
   290  	"1e-350",
   291  	"long:1e-400000",
   292  	// way too small, negative
   293  	"-1e-350",
   294  	"long:-1e-400000",
   295  
   296  	// try to overflow exponent
   297  	// [Disabled: too slow and memory-hungry with rationals.]
   298  	// "1e-4294967296",
   299  	// "1e+4294967296",
   300  	// "1e-18446744073709551616",
   301  	// "1e+18446744073709551616",
   302  
   303  	// https://www.exploringbinary.com/java-hangs-when-converting-2-2250738585072012e-308/
   304  	"2.2250738585072012e-308",
   305  	// https://www.exploringbinary.com/php-hangs-on-numeric-value-2-2250738585072011e-308/
   306  	"2.2250738585072011e-308",
   307  
   308  	// A very large number (initially wrongly parsed by the fast algorithm).
   309  	"4.630813248087435e+307",
   310  
   311  	// A different kind of very large number.
   312  	"22.222222222222222",
   313  	"long:2." + strings.Repeat("2", 4000) + "e+1",
   314  
   315  	// Exactly halfway between 1 and math.Nextafter(1, 2).
   316  	// Round to even (down).
   317  	"1.00000000000000011102230246251565404236316680908203125",
   318  	// Slightly lower; still round down.
   319  	"1.00000000000000011102230246251565404236316680908203124",
   320  	// Slightly higher; round up.
   321  	"1.00000000000000011102230246251565404236316680908203126",
   322  	// Slightly higher, but you have to read all the way to the end.
   323  	"long:1.00000000000000011102230246251565404236316680908203125" + strings.Repeat("0", 10000) + "1",
   324  
   325  	// Smallest denormal, 2^(-1022-52)
   326  	"4.940656458412465441765687928682213723651e-324",
   327  	// Half of smallest denormal, 2^(-1022-53)
   328  	"2.470328229206232720882843964341106861825e-324",
   329  	// A little more than the exact half of smallest denormal
   330  	// 2^-1075 + 2^-1100.  (Rounds to 1p-1074.)
   331  	"2.470328302827751011111470718709768633275e-324",
   332  	// The exact halfway between smallest normal and largest denormal:
   333  	// 2^-1022 - 2^-1075.  (Rounds to 2^-1022.)
   334  	"2.225073858507201136057409796709131975935e-308",
   335  
   336  	"1152921504606846975",  //   1<<60 - 1
   337  	"-1152921504606846975", // -(1<<60 - 1)
   338  	"1152921504606846977",  //   1<<60 + 1
   339  	"-1152921504606846977", // -(1<<60 + 1)
   340  
   341  	"1/3",
   342  }
   343  
   344  // isFinite reports whether f represents a finite rational value.
   345  // It is equivalent to !math.IsNan(f) && !math.IsInf(f, 0).
   346  func isFinite(f float64) bool {
   347  	return math.Abs(f) <= math.MaxFloat64
   348  }
   349  
   350  func TestFloat32SpecialCases(t *testing.T) {
   351  	for _, input := range float64inputs {
   352  		if strings.HasPrefix(input, "long:") {
   353  			if !*long {
   354  				continue
   355  			}
   356  			input = input[len("long:"):]
   357  		}
   358  
   359  		r, ok := new(Rat).SetString(input)
   360  		if !ok {
   361  			t.Errorf("Rat.SetString(%q) failed", input)
   362  			continue
   363  		}
   364  		f, exact := r.Float32()
   365  
   366  		// 1. Check string -> Rat -> float32 conversions are
   367  		// consistent with strconv.ParseFloat.
   368  		// Skip this check if the input uses "a/b" rational syntax.
   369  		if !strings.Contains(input, "/") {
   370  			e64, _ := strconv.ParseFloat(input, 32)
   371  			e := float32(e64)
   372  
   373  			// Careful: negative Rats too small for
   374  			// float64 become -0, but Rat obviously cannot
   375  			// preserve the sign from SetString("-0").
   376  			switch {
   377  			case math.Float32bits(e) == math.Float32bits(f):
   378  				// Ok: bitwise equal.
   379  			case f == 0 && r.Num().BitLen() == 0:
   380  				// Ok: Rat(0) is equivalent to both +/- float64(0).
   381  			default:
   382  				t.Errorf("strconv.ParseFloat(%q) = %g (%b), want %g (%b); delta = %g", input, e, e, f, f, f-e)
   383  			}
   384  		}
   385  
   386  		if !isFinite(float64(f)) {
   387  			continue
   388  		}
   389  
   390  		// 2. Check f is best approximation to r.
   391  		if !checkIsBestApprox32(t, f, r) {
   392  			// Append context information.
   393  			t.Errorf("(input was %q)", input)
   394  		}
   395  
   396  		// 3. Check f->R->f roundtrip is non-lossy.
   397  		checkNonLossyRoundtrip32(t, f)
   398  
   399  		// 4. Check exactness using slow algorithm.
   400  		if wasExact := new(Rat).SetFloat64(float64(f)).Cmp(r) == 0; wasExact != exact {
   401  			t.Errorf("Rat.SetString(%q).Float32().exact = %t, want %t", input, exact, wasExact)
   402  		}
   403  	}
   404  }
   405  
   406  func TestFloat64SpecialCases(t *testing.T) {
   407  	for _, input := range float64inputs {
   408  		if strings.HasPrefix(input, "long:") {
   409  			if !*long {
   410  				continue
   411  			}
   412  			input = input[len("long:"):]
   413  		}
   414  
   415  		r, ok := new(Rat).SetString(input)
   416  		if !ok {
   417  			t.Errorf("Rat.SetString(%q) failed", input)
   418  			continue
   419  		}
   420  		f, exact := r.Float64()
   421  
   422  		// 1. Check string -> Rat -> float64 conversions are
   423  		// consistent with strconv.ParseFloat.
   424  		// Skip this check if the input uses "a/b" rational syntax.
   425  		if !strings.Contains(input, "/") {
   426  			e, _ := strconv.ParseFloat(input, 64)
   427  
   428  			// Careful: negative Rats too small for
   429  			// float64 become -0, but Rat obviously cannot
   430  			// preserve the sign from SetString("-0").
   431  			switch {
   432  			case math.Float64bits(e) == math.Float64bits(f):
   433  				// Ok: bitwise equal.
   434  			case f == 0 && r.Num().BitLen() == 0:
   435  				// Ok: Rat(0) is equivalent to both +/- float64(0).
   436  			default:
   437  				t.Errorf("strconv.ParseFloat(%q) = %g (%b), want %g (%b); delta = %g", input, e, e, f, f, f-e)
   438  			}
   439  		}
   440  
   441  		if !isFinite(f) {
   442  			continue
   443  		}
   444  
   445  		// 2. Check f is best approximation to r.
   446  		if !checkIsBestApprox64(t, f, r) {
   447  			// Append context information.
   448  			t.Errorf("(input was %q)", input)
   449  		}
   450  
   451  		// 3. Check f->R->f roundtrip is non-lossy.
   452  		checkNonLossyRoundtrip64(t, f)
   453  
   454  		// 4. Check exactness using slow algorithm.
   455  		if wasExact := new(Rat).SetFloat64(f).Cmp(r) == 0; wasExact != exact {
   456  			t.Errorf("Rat.SetString(%q).Float64().exact = %t, want %t", input, exact, wasExact)
   457  		}
   458  	}
   459  }
   460  

View as plain text