1 /*
   2  * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug 4826774
  27  * @summary Numerical tests for hexadecimal inputs to parseDouble, parseFloat
  28  * @author Joseph D. Darcy

  29  */
  30 
  31 
  32 import java.util.regex.*;
  33 
  34 public class ParseHexFloatingPoint {
  35     private ParseHexFloatingPoint(){}
  36 
  37     public static final double infinityD = Double.POSITIVE_INFINITY;
  38     public static final double NaND = Double.NaN;
  39 
  40     static int test(String testName, String input,
  41                     double result, double expected) {
  42         int failures =0;
  43 
  44         if (Double.compare(result, expected) != 0 ) {
  45             System.err.println("Failure for " + testName +
  46                                ": For input " + input +
  47                                " expected " + expected +
  48                                " got " + result + ".");
  49         }
  50 
  51         return failures;
  52     }
  53 
  54     static int testCase(String input, double expected) {
  55         int failures =0;
  56 
  57 
  58         // Try different combination of letter components
  59         input = input.toLowerCase(java.util.Locale.US);
  60 
  61         String [] suffices = {"", "f", "F", "d", "D"};
  62         String [] signs = {"", "-", "+"};
  63 
  64         for(int i = 0; i < 2; i++) {
  65             String s1 = input;
  66             if(i == 1)
  67                 s1 = s1.replace('x', 'X');
  68 
  69             for(int j = 0; j < 2; j++) {
  70                 String s2 = s1;
  71                 if(j == 1)
  72                     s2 = s2.replace('p', 'P');
  73 
  74                 for(int k = 0; k < 2; k++) {
  75                     String s3 = s2;
  76                     if(k == 1)
  77                         s3 = upperCaseHex(s3);
  78 
  79 
  80                     for(int m = 0; m < suffices.length; m++) {
  81                         String s4 = s3 + suffices[m];
  82 
  83 
  84                         for(int n = 0; n < signs.length; n++) {
  85                             String s5 = signs[n] + s4;
  86 
  87                             double result = Double.parseDouble(s5);
  88                             failures += test("Double.parseDouble",
  89                                              s5, result, (signs[n].equals("-") ?
  90                                                           -expected:
  91                                                           expected));
  92                         }
  93                     }
  94                 }
  95             }
  96         }
  97 
  98         return failures;
  99     }
 100 
 101     static String upperCaseHex(String s) {
 102         return s.replace('a', 'A').replace('b', 'B').replace('c', 'C').
 103                  replace('d', 'D').replace('e','E').replace('f', 'F');
 104     }
 105 
 106     /*
 107      * Test easy and tricky double rounding cases.
 108      */
 109     static int doubleTests() {
 110 
 111         /*
 112          * A String, double pair
 113          */
 114         class PairSD {
 115             public String s;
 116             public double d;
 117             PairSD(String s, double d) {
 118                 this.s = s;
 119                 this.d = d;
 120             }
 121         }
 122         int failures = 0;
 123 
 124 
 125 
 126         // Hex strings that convert to three; test basic functionality
 127         // of significand and exponent shift adjusts along with the
 128         // no-op of adding leading zeros.  These cases don't exercise
 129         // the rounding code.
 130         String leadingZeros = "0x0000000000000000000";
 131         String [] threeTests = {
 132             "0x.003p12",
 133             "0x.006p11",
 134             "0x.00cp10",
 135             "0x.018p9",
 136 
 137             "0x.3p4",
 138             "0x.6p3",
 139             "0x.cp2",
 140             "0x1.8p1",
 141 
 142             "0x3p0",
 143             "0x6.0p-1",
 144             "0xc.0p-2",
 145             "0x18.0p-3",
 146 
 147             "0x3000000p-24",
 148             "0x3.0p0",
 149             "0x3.000000p0",
 150         };
 151         for(int i=0; i < threeTests.length; i++) {
 152             String input = threeTests[i];
 153             failures += testCase(input, 3.0);
 154 
 155             input.replaceFirst("^0x", leadingZeros);
 156             failures += testCase(input, 3.0);
 157         }
 158 
 159         long bigExponents [] = {
 160             2*Double.MAX_EXPONENT,
 161             2*Double.MIN_EXPONENT,
 162 
 163             (long)Integer.MAX_VALUE-1,
 164             (long)Integer.MAX_VALUE,
 165             (long)Integer.MAX_VALUE+1,
 166 
 167             (long)Integer.MIN_VALUE-1,
 168             (long)Integer.MIN_VALUE,
 169             (long)Integer.MIN_VALUE+1,
 170 
 171             Long.MAX_VALUE-1,
 172             Long.MAX_VALUE,
 173 
 174             Long.MIN_VALUE+1,
 175             Long.MIN_VALUE,
 176         };
 177 
 178         // Test zero significand with large exponents.
 179         for(int i = 0; i < bigExponents.length; i++) {
 180             failures += testCase("0x0.0p"+Long.toString(bigExponents[i]) , 0.0);
 181         }
 182 
 183         // Test nonzero significand with large exponents.
 184         for(int i = 0; i < bigExponents.length; i++) {
 185             long exponent = bigExponents[i];
 186             failures += testCase("0x10000.0p"+Long.toString(exponent) ,
 187                                  (exponent <0?0.0:infinityD));
 188         }
 189 
 190         // Test significands with different lengths and bit patterns.
 191         {
 192             long signif = 0;
 193                 for(int i = 1; i <= 0xe; i++) {
 194                     signif = (signif <<4) | (long)i;
 195                     failures += testCase("0x"+Long.toHexString(signif)+"p0", signif);
 196                 }
 197         }
 198 
 199         PairSD [] testCases = {
 200             new PairSD("0x0.0p0",               0.0/16.0),
 201             new PairSD("0x0.1p0",               1.0/16.0),
 202             new PairSD("0x0.2p0",               2.0/16.0),
 203             new PairSD("0x0.3p0",               3.0/16.0),
 204             new PairSD("0x0.4p0",               4.0/16.0),
 205             new PairSD("0x0.5p0",               5.0/16.0),
 206             new PairSD("0x0.6p0",               6.0/16.0),
 207             new PairSD("0x0.7p0",               7.0/16.0),
 208             new PairSD("0x0.8p0",               8.0/16.0),
 209             new PairSD("0x0.9p0",               9.0/16.0),
 210             new PairSD("0x0.ap0",               10.0/16.0),
 211             new PairSD("0x0.bp0",               11.0/16.0),
 212             new PairSD("0x0.cp0",               12.0/16.0),
 213             new PairSD("0x0.dp0",               13.0/16.0),
 214             new PairSD("0x0.ep0",               14.0/16.0),
 215             new PairSD("0x0.fp0",               15.0/16.0),
 216 
 217             // Half-way case between zero and MIN_VALUE rounds down to
 218             // zero
 219             new PairSD("0x1.0p-1075",           0.0),
 220 
 221             // Slighly more than half-way case between zero and
 222             // MIN_VALUES rounds up to zero.
 223             new PairSD("0x1.1p-1075",                   Double.MIN_VALUE),
 224             new PairSD("0x1.000000000001p-1075",        Double.MIN_VALUE),
 225             new PairSD("0x1.000000000000001p-1075",     Double.MIN_VALUE),
 226 
 227             // More subnormal rounding tests
 228             new PairSD("0x0.fffffffffffff7fffffp-1022", Math.nextDown(Double.MIN_NORMAL)),
 229             new PairSD("0x0.fffffffffffff8p-1022",      Double.MIN_NORMAL),
 230             new PairSD("0x0.fffffffffffff800000001p-1022",Double.MIN_NORMAL),
 231             new PairSD("0x0.fffffffffffff80000000000000001p-1022",Double.MIN_NORMAL),
 232             new PairSD("0x1.0p-1022",                   Double.MIN_NORMAL),
 233 
 234 
 235             // Large value and overflow rounding tests
 236             new PairSD("0x1.fffffffffffffp1023",        Double.MAX_VALUE),
 237             new PairSD("0x1.fffffffffffff0000000p1023", Double.MAX_VALUE),
 238             new PairSD("0x1.fffffffffffff4p1023",       Double.MAX_VALUE),
 239             new PairSD("0x1.fffffffffffff7fffffp1023",  Double.MAX_VALUE),
 240             new PairSD("0x1.fffffffffffff8p1023",       infinityD),
 241             new PairSD("0x1.fffffffffffff8000001p1023", infinityD),
 242 
 243             new PairSD("0x1.ffffffffffffep1023",        Math.nextDown(Double.MAX_VALUE)),
 244             new PairSD("0x1.ffffffffffffe0000p1023",    Math.nextDown(Double.MAX_VALUE)),
 245             new PairSD("0x1.ffffffffffffe8p1023",       Math.nextDown(Double.MAX_VALUE)),
 246             new PairSD("0x1.ffffffffffffe7p1023",       Math.nextDown(Double.MAX_VALUE)),
 247             new PairSD("0x1.ffffffffffffeffffffp1023",  Double.MAX_VALUE),
 248             new PairSD("0x1.ffffffffffffe8000001p1023", Double.MAX_VALUE),
 249         };
 250 
 251         for (int i = 0; i < testCases.length; i++) {
 252             failures += testCase(testCases[i].s,testCases[i].d);
 253         }
 254 
 255         failures += significandAlignmentTests();
 256 
 257         {
 258             java.util.Random rand = new java.util.Random();
 259             // Consistency check; double => hexadecimal => double
 260             // preserves the original value.
 261             for(int i = 0; i < 1000; i++) {
 262                 double d = rand.nextDouble();
 263                 failures += testCase(Double.toHexString(d), d);
 264             }
 265         }
 266 
 267         return failures;
 268     }
 269 
 270     /*
 271      * Verify rounding works the same regardless of how the
 272      * significand is aligned on input.  A useful extension could be
 273      * to have this sort of test for strings near the overflow
 274      * threshold.
 275      */
 276     static int significandAlignmentTests() {
 277         int failures = 0;
 278                 // baseSignif * 2^baseExp = nextDown(2.0)
 279         long [] baseSignifs = {
 280             0x1ffffffffffffe00L,
 281             0x1fffffffffffff00L
 282         };
 283 
 284         double [] answers = {
 285             Math.nextDown(Math.nextDown(2.0)),
 286             Math.nextDown(2.0),
 287             2.0
 288         };
 289 
 290         int baseExp = -60;
 291         int count = 0;
 292         for(int i = 0; i < 2; i++) {
 293             for(long j = 0; j <= 0xfL; j++) {
 294                 for(long k = 0; k <= 8; k+= 4) { // k = {0, 4, 8}
 295                     long base = baseSignifs[i];
 296                     long testValue = base | (j<<4) | k;
 297 
 298                     int offset = 0;
 299                     // Calculate when significand should be incremented
 300                     // see table 4.7 in Koren book
 301 
 302                     if ((base & 0x100L) == 0L ) { // lsb is 0
 303                         if ( (j >= 8L) &&         // round is 1
 304                              ((j & 0x7L) != 0 || k != 0 ) ) // sticky is 1
 305                             offset = 1;
 306                     }
 307                     else {                        // lsb is 1
 308                         if (j >= 8L)              // round is 1
 309                             offset = 1;
 310                     }
 311 
 312                     double expected = answers[i+offset];
 313 
 314                     for(int m = -2; m <= 3; m++) {
 315                         count ++;
 316 
 317                         // Form equal value string and evaluate it
 318                         String s = "0x" +
 319                             Long.toHexString((m >=0) ?(testValue<<m):(testValue>>(-m))) +
 320                             "p" + (baseExp - m);
 321 
 322                         failures += testCase(s, expected);
 323                     }
 324                 }
 325             }
 326         }
 327 
 328         return failures;
 329     }
 330 
 331 
 332     /*
 333      * Test tricky float rounding cases.  The code which
 334      * reads in a hex string converts the string to a double value.
 335      * If a float value is needed, the double value is cast to float.
 336      * However, the cast be itself not always guaranteed to return the
 337      * right result since:
 338      *
 339      * 1. hex string => double can discard a sticky bit which would
 340      * influence a direct hex string => float conversion.
 341      *
 342      * 2. hex string => double => float can have a rounding to double
 343      * precision which results in a larger float value while a direct
 344      * hex string => float conversion would not round up.
 345      *
 346      * This method includes tests of the latter two possibilities.
 347      */
 348     static int floatTests(){
 349         int failures = 0;
 350 
 351         /*
 352          * A String, float pair
 353          */
 354         class PairSD {
 355             public String s;
 356             public float f;
 357             PairSD(String s, float f) {
 358                 this.s = s;
 359                 this.f = f;
 360             }
 361         }
 362 
 363         String [][] roundingTestCases = {
 364             // Target float value       hard rouding version
 365 
 366             {"0x1.000000p0",    "0x1.0000000000001p0"},
 367 
 368             // Try some values that should round up to nextUp(1.0f)
 369             {"0x1.000002p0",    "0x1.0000010000001p0"},
 370             {"0x1.000002p0",    "0x1.00000100000008p0"},
 371             {"0x1.000002p0",    "0x1.0000010000000fp0"},
 372             {"0x1.000002p0",    "0x1.00000100000001p0"},
 373             {"0x1.000002p0",    "0x1.00000100000000000000000000000000000000001p0"},
 374             {"0x1.000002p0",    "0x1.0000010000000fp0"},
 375 
 376             // Potential double rounding cases
 377             {"0x1.000002p0",    "0x1.000002fffffffp0"},
 378             {"0x1.000002p0",    "0x1.000002fffffff8p0"},
 379             {"0x1.000002p0",    "0x1.000002ffffffffp0"},
 380 
 381             {"0x1.000002p0",    "0x1.000002ffff0ffp0"},
 382             {"0x1.000002p0",    "0x1.000002ffff0ff8p0"},
 383             {"0x1.000002p0",    "0x1.000002ffff0fffp0"},
 384 
 385 
 386             {"0x1.000000p0",    "0x1.000000fffffffp0"},
 387             {"0x1.000000p0",    "0x1.000000fffffff8p0"},
 388             {"0x1.000000p0",    "0x1.000000ffffffffp0"},
 389 
 390             {"0x1.000000p0",    "0x1.000000ffffffep0"},
 391             {"0x1.000000p0",    "0x1.000000ffffffe8p0"},
 392             {"0x1.000000p0",    "0x1.000000ffffffefp0"},
 393 
 394             // Float subnormal cases
 395             {"0x0.000002p-126", "0x0.0000010000001p-126"},
 396             {"0x0.000002p-126", "0x0.00000100000000000001p-126"},
 397 
 398             {"0x0.000006p-126", "0x0.0000050000001p-126"},
 399             {"0x0.000006p-126", "0x0.00000500000000000001p-126"},
 400 
 401             {"0x0.0p-149",      "0x0.7ffffffffffffffp-149"},
 402             {"0x1.0p-148",      "0x1.3ffffffffffffffp-148"},
 403             {"0x1.cp-147",      "0x1.bffffffffffffffp-147"},
 404 
 405             {"0x1.fffffcp-127", "0x1.fffffdffffffffp-127"},
 406         };
 407 
 408         String [] signs = {"", "-"};
 409 
 410         for(int i = 0; i < roundingTestCases.length; i++) {
 411             for(int j = 0; j < signs.length; j++) {
 412                 String expectedIn = signs[j]+roundingTestCases[i][0];
 413                 String resultIn   = signs[j]+roundingTestCases[i][1];
 414 
 415                 float expected =  Float.parseFloat(expectedIn);
 416                 float result   =  Float.parseFloat(resultIn);
 417 
 418                 if( Float.compare(expected, result) != 0) {
 419                     failures += 1;
 420                     System.err.println("" + (i+1));
 421                     System.err.println("Expected = " + Float.toHexString(expected));
 422                     System.err.println("Rounded  = " + Float.toHexString(result));
 423                     System.err.println("Double   = " + Double.toHexString(Double.parseDouble(resultIn)));
 424                     System.err.println("Input    = " + resultIn);
 425                     System.err.println("");
 426                 }
 427             }
 428         }
 429 
 430         return failures;
 431     }
 432 
 433     public static void main(String argv[]) {
 434         int failures = 0;
 435 
 436         failures += doubleTests();
 437         failures += floatTests();
 438 
 439         if (failures != 0) {
 440             throw new RuntimeException("" + failures + " failures while " +
 441                                        "testing hexadecimal floating-point " +
 442                                        "parsing.");
 443         }
 444     }
 445 
 446 }
--- EOF ---