Path: blob/master/test/jdk/java/util/Random/RandomNextDoubleBoundary.java
66644 views
/*1* Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary Verify nextDouble stays within range26* @bug 8280550 8280950 828118327*/2829import java.util.SplittableRandom;30import java.util.random.RandomGenerator;3132public class RandomNextDoubleBoundary {33public static void main(String... args) {34negativeBounds();35positiveBounds();36}3738private static void negativeBounds() {39// Both bounds are negative40double lowerBound = -1.0000000000000002;41double upperBound = -1.0;42var sr = new SplittableRandom(42L);43var r = sr.nextDouble(lowerBound, upperBound);4445if (r >= upperBound) {46System.err.println("r = " + r + "\t" + Double.toHexString(r));47System.err.println("ub = " + upperBound + "\t" + Double.toHexString(upperBound));48throw new RuntimeException("Greater than upper bound");49}5051if (r < lowerBound) {52System.err.println("r = " + r + "\t" + Double.toHexString(r));53System.err.println("lb = " + lowerBound + "\t" + Double.toHexString(lowerBound));54throw new RuntimeException("Less than lower bound");55}56}5758private static void positiveBounds() {59double[][] originAndBounds = {{10, 100},60{12345, 123456},61{5432167.234, 54321678.1238}};62for (double[] originAndBound : originAndBounds) {63nextDoublesWithRange(originAndBound[0], originAndBound[1]);64}65}6667public static void nextDoublesWithRange(double origin, double bound) {68RandomGenerator rg = new RandomGenerator() {69@Override70public double nextDouble() {71return Double.MAX_VALUE;72}7374@Override75public long nextLong() {76return 0;77}78};79double value = rg.nextDouble(origin, bound);8081if (bound > 0) {82value = rg.nextDouble(bound); // Equivalent to nextDouble(0.0, bound)83assertTrue(value >= 0.0);84assertTrue(value < bound);85}86}8788public static void assertTrue(boolean condition) {89if (!condition) {90throw new AssertionError();91}92}93}949596