1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 18 package com.hp.creals; 19 20 import junit.framework.AssertionFailedError; 21 import junit.framework.TestCase; 22 23 import java.util.Random; 24 25 public class ConversionTest extends TestCase { 26 private static void check(boolean x, String s) { 27 if (!x) throw new AssertionFailedError(s); 28 } 29 final static int NRANDOM = 100; // Number of random values to 30 // test. Bigger ==> slower 31 final CR BIG = CR.valueOf(Double.MAX_VALUE); 32 final CR HUGE = BIG.multiply(BIG); 33 final CR TINY = CR.ONE.shiftRight(1078); 34 35 public void checkDoubleConversion(double x) { 36 if (!Double.isNaN(x) && !Double.isInfinite(x)) { 37 CR crValue = CR.valueOf(x); 38 check(x == crValue.doubleValue(), "double conversion: " + x); 39 } 40 } 41 42 public void checkFloatConversion(float f) { 43 if (!Float.isNaN(f) && !Float.isInfinite(f)) { 44 CR crValue = CR.valueOf(f); 45 check(f == crValue.floatValue(), "float conversion: " + f); 46 } 47 } 48 49 public void checkNearbyConversions(double x) { 50 checkDoubleConversion(x); 51 checkDoubleConversion(Math.nextAfter(x, Double.NEGATIVE_INFINITY)); 52 checkDoubleConversion(Math.nextAfter(x, Double.POSITIVE_INFINITY)); 53 float f = (float)x; 54 checkFloatConversion(f); 55 checkFloatConversion(Math.nextAfter(f, Double.NEGATIVE_INFINITY)); 56 checkFloatConversion(Math.nextAfter(f, Double.POSITIVE_INFINITY)); 57 } 58 59 public void testConversions() { 60 check(TINY.doubleValue() == 0.0d, "Tiny.doubleValue()"); 61 checkNearbyConversions(0.0d); 62 checkNearbyConversions(Double.MAX_VALUE); 63 checkNearbyConversions(Double.MIN_VALUE); 64 check(HUGE.doubleValue() == Double.POSITIVE_INFINITY, 65 "double +infinity"); 66 check(HUGE.negate().doubleValue() == Double.NEGATIVE_INFINITY, 67 "double -infinity"); 68 check(HUGE.floatValue() == Float.POSITIVE_INFINITY, 69 "float +infinity"); 70 check(HUGE.negate().floatValue() == Float.NEGATIVE_INFINITY, 71 "float -infinity"); 72 for (double x = 1.0d; x != 0.0d; x /= 2.0d) { 73 checkNearbyConversions(x); 74 } 75 for (double x = -1.0d; x != Double.NEGATIVE_INFINITY; x *= 2.0d) { 76 checkNearbyConversions(x); 77 } 78 Random r = new Random(); // Random seed! 79 for (int i = 0; i < NRANDOM; ++i) { 80 double d = Math.exp(1000.0 * r.nextDouble()); 81 if (r.nextBoolean()) d = -d; 82 checkNearbyConversions(d); 83 } 84 } 85 } 86