1/*
2 * Copyright (C) 2011 The Guava Authors
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
17package com.google.common.math;
18
19import java.math.BigInteger;
20import java.util.Random;
21
22/**
23 * Utilities for benchmarks.
24 *
25 * @author Louis Wasserman
26 */
27final class MathBenchmarking {
28  static final int ARRAY_SIZE = 0x10000;
29  static final int ARRAY_MASK = 0x0ffff;
30  static final Random RANDOM_SOURCE = new Random(314159265358979L);
31  static final int MAX_EXPONENT = 100;
32
33  /*
34   * Duplicated from LongMath.
35   * binomial(biggestBinomials[k], k) fits in a long, but not
36   * binomial(biggestBinomials[k] + 1, k).
37   */
38  static final int[] biggestBinomials =
39      {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733,
40          887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68,
41          67, 67, 66, 66, 66, 66};
42
43  static BigInteger randomPositiveBigInteger(int numBits) {
44    int digits = RANDOM_SOURCE.nextInt(numBits) + 1;
45    return new BigInteger(digits, RANDOM_SOURCE).add(BigInteger.ONE);
46  }
47
48  static BigInteger randomNonNegativeBigInteger(int numBits) {
49    int digits = RANDOM_SOURCE.nextInt(numBits) + 1;
50    return new BigInteger(digits, RANDOM_SOURCE);
51  }
52
53  static BigInteger randomNonZeroBigInteger(int numBits) {
54    BigInteger result = randomPositiveBigInteger(numBits);
55    return RANDOM_SOURCE.nextBoolean() ? result : result.negate();
56  }
57
58  static BigInteger randomBigInteger(int numBits) {
59    BigInteger result = randomNonNegativeBigInteger(numBits);
60    return RANDOM_SOURCE.nextBoolean() ? result : result.negate();
61  }
62
63  static double randomDouble(int maxExponent) {
64    return RANDOM_SOURCE.nextDouble();
65  }
66
67  /**
68   * Returns a random integer between zero and {@code MAX_EXPONENT}.
69   */
70  static int randomExponent() {
71    return RANDOM_SOURCE.nextInt(MAX_EXPONENT + 1);
72  }
73
74  static double randomPositiveDouble() {
75    return Math.exp(randomDouble(6));
76  }
77}
78