AbstractMultivariateRealDistribution.java

  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.math3.distribution;

  18. import org.apache.commons.math3.exception.NotStrictlyPositiveException;
  19. import org.apache.commons.math3.exception.util.LocalizedFormats;
  20. import org.apache.commons.math3.random.RandomGenerator;

  21. /**
  22.  * Base class for multivariate probability distributions.
  23.  *
  24.  * @since 3.1
  25.  */
  26. public abstract class AbstractMultivariateRealDistribution
  27.     implements MultivariateRealDistribution {
  28.     /** RNG instance used to generate samples from the distribution. */
  29.     protected final RandomGenerator random;
  30.     /** The number of dimensions or columns in the multivariate distribution. */
  31.     private final int dimension;

  32.     /**
  33.      * @param rng Random number generator.
  34.      * @param n Number of dimensions.
  35.      */
  36.     protected AbstractMultivariateRealDistribution(RandomGenerator rng,
  37.                                                    int n) {
  38.         random = rng;
  39.         dimension = n;
  40.     }

  41.     /** {@inheritDoc} */
  42.     public void reseedRandomGenerator(long seed) {
  43.         random.setSeed(seed);
  44.     }

  45.     /** {@inheritDoc} */
  46.     public int getDimension() {
  47.         return dimension;
  48.     }

  49.     /** {@inheritDoc} */
  50.     public abstract double[] sample();

  51.     /** {@inheritDoc} */
  52.     public double[][] sample(final int sampleSize) {
  53.         if (sampleSize <= 0) {
  54.             throw new NotStrictlyPositiveException(LocalizedFormats.NUMBER_OF_SAMPLES,
  55.                                                    sampleSize);
  56.         }
  57.         final double[][] out = new double[sampleSize][dimension];
  58.         for (int i = 0; i < sampleSize; i++) {
  59.             out[i] = sample();
  60.         }
  61.         return out;
  62.     }
  63. }