View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.rng.sampling.distribution;
18  
19  import org.apache.commons.rng.UniformRandomProvider;
20  
21  /**
22   * Sampling from an <a href="http://mathworld.wolfram.com/ExponentialDistribution.html">exponential distribution</a>.
23   *
24   * <p>Sampling uses:</p>
25   *
26   * <ul>
27   *   <li>{@link UniformRandomProvider#nextLong()}
28   *   <li>{@link UniformRandomProvider#nextDouble()}
29   * </ul>
30   *
31   * @since 1.0
32   */
33  public class AhrensDieterExponentialSampler
34      extends SamplerBase
35      implements SharedStateContinuousSampler {
36      /**
37       * Table containing the constants
38       * \( q_i = sum_{j=1}^i (\ln 2)^j / j! = \ln 2 + (\ln 2)^2 / 2 + ... + (\ln 2)^i / i! \)
39       * until the largest representable fraction below 1 is exceeded.
40       *
41       * Note that
42       * \( 1 = 2 - 1 = \exp(\ln 2) - 1 = sum_{n=1}^\infinity (\ln 2)^n / n! \)
43       * thus \( q_i \rightarrow 1 as i \rightarrow +\infinity \),
44       * so the higher \( i \), the closer we get to 1 (the series is not alternating).
45       *
46       * By trying, n = 16 in Java is enough to reach 1.
47       */
48      private static final double[] EXPONENTIAL_SA_QI = new double[16];
49      /** The mean of this distribution. */
50      private final double mean;
51      /** Underlying source of randomness. */
52      private final UniformRandomProvider rng;
53  
54      //
55      // Initialize tables.
56      //
57      static {
58          //
59          // Filling EXPONENTIAL_SA_QI table.
60          // Note that we don't want qi = 0 in the table.
61          //
62          final double ln2 = Math.log(2);
63          double qi = 0;
64  
65          // Start with 0!
66          // This will not overflow a long as the length < 21
67          long factorial = 1;
68          for (int i = 0; i < EXPONENTIAL_SA_QI.length; i++) {
69              factorial *= i + 1;
70              qi += Math.pow(ln2, i + 1.0) / factorial;
71              EXPONENTIAL_SA_QI[i] = qi;
72          }
73      }
74  
75      /**
76       * Create an instance.
77       *
78       * @param rng Generator of uniformly distributed random numbers.
79       * @param mean Mean of this distribution.
80       * @throws IllegalArgumentException if {@code mean <= 0}
81       */
82      public AhrensDieterExponentialSampler(UniformRandomProvider rng,
83                                            double mean) {
84          // Validation before java.lang.Object constructor exits prevents partially initialized object
85          this(InternalUtils.requireStrictlyPositive(mean, "mean"), rng);
86      }
87  
88      /**
89       * @param mean Mean.
90       * @param rng Generator of uniformly distributed random numbers.
91       */
92      private AhrensDieterExponentialSampler(double mean,
93                                             UniformRandomProvider rng) {
94          super(null);
95          this.rng = rng;
96          this.mean = mean;
97      }
98  
99      /** {@inheritDoc} */
100     @Override
101     public double sample() {
102         // Step 1:
103         double a = 0;
104         // Avoid u=0 which creates an infinite loop
105         double u = InternalUtils.makeNonZeroDouble(rng.nextLong());
106 
107         // Step 2 and 3:
108         while (u < 0.5) {
109             a += EXPONENTIAL_SA_QI[0];
110             u *= 2;
111         }
112 
113         // Step 4 (now u >= 0.5):
114         u += u - 1;
115 
116         // Step 5:
117         if (u <= EXPONENTIAL_SA_QI[0]) {
118             return mean * (a + u);
119         }
120 
121         // Step 6:
122         int i = 0; // Should be 1, be we iterate before it in while using 0.
123         double u2 = rng.nextDouble();
124         double umin = u2;
125 
126         // Step 7 and 8:
127         do {
128             ++i;
129             u2 = rng.nextDouble();
130 
131             if (u2 < umin) {
132                 umin = u2;
133             }
134 
135             // Step 8:
136         } while (u > EXPONENTIAL_SA_QI[i]); // Ensured to exit since EXPONENTIAL_SA_QI[MAX] = 1.
137 
138         return mean * (a + umin * EXPONENTIAL_SA_QI[0]);
139     }
140 
141     /** {@inheritDoc} */
142     @Override
143     public String toString() {
144         return "Ahrens-Dieter Exponential deviate [" + rng.toString() + "]";
145     }
146 
147     /**
148      * {@inheritDoc}
149      *
150      * @since 1.3
151      */
152     @Override
153     public SharedStateContinuousSampler withUniformRandomProvider(UniformRandomProvider rng) {
154         // Use private constructor without validation
155         return new AhrensDieterExponentialSampler(mean, rng);
156     }
157 
158     /**
159      * Create a new exponential distribution sampler.
160      *
161      * @param rng Generator of uniformly distributed random numbers.
162      * @param mean Mean of the distribution.
163      * @return the sampler
164      * @throws IllegalArgumentException if {@code mean <= 0}
165      * @since 1.3
166      */
167     public static SharedStateContinuousSampler of(UniformRandomProvider rng,
168                                                   double mean) {
169         return new AhrensDieterExponentialSampler(rng, mean);
170     }
171 }