NextDouble()
        {
            double xi, eta;

            do
            {
                double gen1 = 1.0 - RandomSource.NextDouble();
                double gen2 = 1.0 - RandomSource.NextDouble();
                if (gen1 <= _helper2)
                {
                    xi  = Math.Pow(gen1 / _helper2, 1.0 / _helper1);
                    eta = gen2 * Math.Pow(xi, _helper1 - 1.0);
                }
                else
                {
                    xi  = 1.0 - Math.Log((gen1 - _helper2) / (1.0 - _helper2));
                    eta = gen2 * Math.Pow(Math.E, -xi);
                }
            }while(eta > Math.Pow(xi, _helper1 - 1.0) * Math.Pow(Math.E, -xi));

            for (int i = 1; i <= _alpha; i++)
            {
                xi -= Math.Log(RandomSource.NextDouble());
            }

            return(xi * _theta);
        }
Exemplo n.º 2
0
 public void Samples(double[] values)
 {
     for (int i = 0; i < values.Length; i++)
     {
         values[i] = InverseCumulativeDistribution(RandomSource.NextDouble());
     }
 }
        NextDouble()
        {
            // Note that this method generate two gaussian deviates
            // at once. The additional deviate is recorded in
            // <c>extraNormal</c>.

            // Using the extra gaussian deviate if available
            if (_extraNormal.HasValue)
            {
                double extraNormalCpy = _extraNormal.Value;
                _extraNormal = null;
                return(extraNormalCpy);
            }

            // Generating two new gaussian deviates
            double rsq, v1, v2;

            // We need a non-zero random point inside the unit circle.
            do
            {
                v1  = (2.0 * RandomSource.NextDouble()) - 1.0;
                v2  = (2.0 * RandomSource.NextDouble()) - 1.0;
                rsq = (v1 * v1) + (v2 * v2);
            }while(rsq > 1.0 || rsq == 0);

            // Make the Box-Muller transformation
            double fac = Math.Sqrt(-2.0 * Math.Log(rsq) / rsq);

            _extraNormal = v1 * fac;
            return(v2 * fac);
        }
        /// <summary>
        /// Returns a sample from the distribution P.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">When the algorithms detects that the proposal
        /// distribution doesn't upper bound the target distribution.</exception>
        public override T Sample()
        {
            while (true)
            {
                // Get a sample from the proposal.
                T x = _proposal();
                // Evaluate the density for proposal.
                double q = _pdfQ(x);
                // Evaluate the density for the target density.
                double p = _pdfP(x);
                // Sample a variable between 0.0 and proposal density.
                double u = RandomSource.NextDouble() * q;

                Samples++;

                if (q < p)
                {
                    throw new ArgumentException("The sampler\'s proposal distribution is not upper bounding the target density.");
                }
                if (u < p)
                {
                    Accepts++;
                    return(x);
                }
            }
        }
        RandomPermutation(
            int n
            )
        {
            if (n < 0)
            {
                throw new ArgumentOutOfRangeException("size", n, Resources.ArgumentNotNegative);
            }

            IndexedValue[] indexedValues = new IndexedValue[n];
            for (int i = 0; i < indexedValues.Length; i++)
            {
                indexedValues[i] = new IndexedValue(i, _random.NextDouble());
            }

            // sorting the array (act as a random permutation)
            Array.Sort(indexedValues);

            // creating and returning the permutation
            int[] permutation = new int[n];
            for (int i = 0; i < n; i++)
            {
                permutation[i] = indexedValues[i].Index;
            }

            return(permutation);
        }
        /// <summary>
        /// Returns a sample from the distribution P.
        /// </summary>
        /// <exception cref="ArgumentOutOfRangeException">When the algorithms detects that the proposal
        /// distribution doesn't upper bound the target distribution.</exception>
        public override T Sample()
        {
            while (true)
            {
                // Get a sample from the proposal.
                T x = _proposal();
                // Evaluate the density for proposal.
                double q = _pdfQ(x);
                // Evaluate the density for the target density.
                double p = _pdfP(x);
                // Sample a variable between 0.0 and proposal density.
                double u = RandomSource.NextDouble() * q;

                Samples++;

                if (q < p)
                {
                    throw new ArgumentOutOfRangeException(Resources.ProposalDistributionNoUpperBound);
                }
                if (u < p)
                {
                    Accepts++;
                    return(x);
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Returns the next zipfian deviate.
        /// </summary>
        public double Next()
        {
            /* A transformation method (similar to the exponential
             * generator) is used here to generate a zipfian deviate. */

            double p = _random.NextDouble();

            return(Math.Pow(1d - p, 1d / (1d - _skew)));
        }
        NextInt32()
        {
            if (RandomSource.NextDouble() < _p)
            {
                return(1);
            }

            return(0);
        }
Exemplo n.º 9
0
        NextInt32()
        {
            int count = 0;

            for (double product = RandomSource.NextDouble(); product >= _helper1; product *= RandomSource.NextDouble())
            {
                count++;
            }

            return(count);
        }
        NextDouble()
        {
            double genNum = RandomSource.NextDouble();

            if (genNum <= _lowerPart / _diff)
            {
                return(_a + (Math.Sqrt(genNum) * _helper3));
            }

            return(_b - (Math.Sqrt((genNum * _diff) - _lowerPart) * _helper4));
        }
Exemplo n.º 11
0
        NextInt32()
        {
            // TODO: Implement direct transformation instead of simulation
            int samples;

            for (samples = 1; RandomSource.NextDouble() >= _p; samples++)
            {
            }

            return(samples);
        }
        NextDouble()
        {
            double product = 1.0;

            for (int i = 0; i < _shape; i++)
            {
                // Subtract random number from 1.0 to avoid Math.Log(0.0)
                product *= (1.0 - RandomSource.NextDouble());
            }

            return(_helper1 * Math.Log(product));
        }
        /// <summary>
        /// This method runs the sampler for a number of iterations without returning a sample
        /// </summary>
        private void Burn(int n)
        {
            for (int i = 0; i < n; i++)
            {
                double x_l  = mCurrent;
                double x_r  = mCurrent;
                double xnew = mCurrent;

                // The logarithm of the slice height.
                double lu = System.Math.Log(RandomSource.NextDouble()) + mCurrentDensityLn;

                // Create a horizontal interval (x_l, x_r) enclosing x.
                double r = RandomSource.NextDouble();
                x_l = mCurrent - r * Scale;
                x_r = mCurrent + (1.0 - r) * Scale;

                // Stepping out procedure.
                while (mPdfLnP(x_l) > lu)
                {
                    x_l -= Scale;
                }
                while (mPdfLnP(x_r) > lu)
                {
                    x_r += Scale;
                }

                // Shrinking: propose new x and shrink interval until good one found.
                while (true)
                {
                    xnew = RandomSource.NextDouble() * (x_r - x_l) + x_l;
                    mCurrentDensityLn = mPdfLnP(xnew);
                    if (mCurrentDensityLn > lu)
                    {
                        mCurrent = xnew;
                        mAccepts++;
                        mSamples++;
                        break;
                    }
                    if (xnew > mCurrent)
                    {
                        x_r = xnew;
                    }
                    else
                    {
                        x_l = xnew;
                    }
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// This method runs the sampler for a number of iterations without returning a sample
        /// </summary>
        private void Burn(int n)
        {
            for (int i = 0; i < n; i++)
            {
                // The logarithm of the slice height.
                double lu = Math.Log(RandomSource.NextDouble()) + _currentDensityLn;

                // Create a horizontal interval (x_l, x_r) enclosing x.
                double r  = RandomSource.NextDouble();
                double xL = _current - r * Scale;
                double xR = _current + (1.0 - r) * Scale;

                // Stepping out procedure.
                while (_pdfLnP(xL) > lu)
                {
                    xL -= Scale;
                }
                while (_pdfLnP(xR) > lu)
                {
                    xR += Scale;
                }

                // Shrinking: propose new x and shrink interval until good one found.
                while (true)
                {
                    double xnew = RandomSource.NextDouble() * (xR - xL) + xL;
                    _currentDensityLn = _pdfLnP(xnew);
                    if (_currentDensityLn > lu)
                    {
                        _current = xnew;
                        Accepts++;
                        Samples++;
                        break;
                    }
                    if (xnew > _current)
                    {
                        xR = xnew;
                    }
                    else
                    {
                        xL = xnew;
                    }
                }
            }
        }
        NextInt32()
        {
            double rnd = RandomSource.NextDouble();

            if (rnd >= _cdf[_n - 1])
            {
                return(_last);
            }

            // TODO: consider using binary search instead
            int index = 0;

            while (_cdf[index] < rnd)
            {
                index++;
            }

            return(index + _first);
        }
Exemplo n.º 16
0
 public double Sample()
 {
     return(InverseCumulativeDistribution(RandomSource.NextDouble()));
 }
Exemplo n.º 17
0
 NextDouble()
 {
     // Subtract random number from 1.0 to avoid Math.Log(0.0)
     return(_helper1 * Math.Log(1.0 - RandomSource.NextDouble()));
 }
Exemplo n.º 18
0
 NextDouble()
 {
     return(_sigma * Math.Sqrt(-2 * Math.Log(1 - RandomSource.NextDouble())));
 }
Exemplo n.º 19
0
        NextInt32()
        {
            // TODO: Implement direct transformation instead of simulation
            int successes = 0;

            for (int i = 0; i < _n; i++)
            {
                if (RandomSource.NextDouble() < _p)
                {
                    successes++;
                }
            }

            return(successes);

            // ALTERNATIVE IMPLEMENTATION (by Thaddaeus Parker/NR), CONSIDER USE THIS INSTEAD:

            /*
             *
             *
             * /// <summary>
             * /// Returns a number from an integer value that is a random deviate drawn from a binomial distribution of
             * /// numTrials each of probability "probability", using the System.Random as a source of uniform random deviates.
             * /// </summary>
             * /// <param name="probability">The probability of each trial</param>
             * /// <param name="numberTrials">The number of trials to perform</param>
             * /// <returns>A binomial deviated floating point number</returns>
             * public double Next(double probability, int numberTrials)
             * {
             * double inProbability; //used for the next function
             *
             * double amount, //the mean deviate to produce
             *  em,
             *  angle,  //an angle that is temporarily calculated for each iteration
             *  binomial; //the binomial return value
             * int count = 0;
             * double tmp; //used for gathering temporary deviations
             * double yangle; //used for finding tmp value
             * double root; //finds the root of amount of trials for the probability cause
             * //reset the probability and number of trials but keep the same seed.
             * _probability = (probability <= 0.5d) ? probability : 1.0 - probability;
             * amount = numberTrials * _probability;  //mean deviate produced
             * _numberTrials = numberTrials;
             * inProbability = probability;
             * if(_numberTrials < 25)
             * {  //use the direct method while numberTrials is not too large
             *  binomial = 0.0;
             *  for(count = 1; count <= _numberTrials; count++)
             *  {
             *      if(random.NextDouble() < _probability)
             ++binomial;
             *  }
             * }
             * else if(amount < 1.0)
             * {  //if fewer than one event is expected our of 25+ trials, then the distribution
             *  //is quite accurately Poisson.  Use the direct Poisson method
             *  double g = System.Math.Exp(-amount);
             *  double t = 1.0;
             *  for(count = 0; count <= _numberTrials; count++)
             *  {
             *      t *= random.NextDouble();
             *      if(t < g)
             *          break;
             *  }
             *  binomial = ((count <= _numberTrials) ? count : _numberTrials);
             * }
             * else
             * {
             *  //use rejection method
             *  if(_numberTrials != oldNumber)
             *  {  //if numberTrials has changed then compute useful quantities
             *      en = numberTrials;
             *      oldGamma = Fn.GammaLn(en + 1.0);
             *      oldNumber = numberTrials;
             *  }
             *  if(_probability != oldProbability)
             *  {  //if _probability has changed, then compute useful quantities
             *      pc = 1.0 - _probability;
             *      probabilityLog = System.Math.Log(_probability);
             *      pclog = System.Math.Log(pc);
             *      oldProbability = _probability;
             *  }
             *  root = System.Math.Sqrt(2.0 * amount * pc);
             *  do
             *  {     // The following code is rejection method with a lorentzian comparison function
             *      do
             *      {
             *          angle = System.Math.PI * random.NextDouble();
             *          yangle = System.Math.Tan(angle);
             *          em = root * yangle + amount; //trick for integer distribution
             *      } while(em < 0.0 || em >= (en + 1.0)); //reject
             *      em = System.Math.Floor(em);
             *      tmp = 1.2 * root * (1.0 + yangle * yangle) * System.Math.Exp(oldGamma - Fn.GammaLn(em + 1.0) - Fn.GammaLn(en - em + 1.0) + em * probabilityLog + (en - em) * pclog);
             *  } while(random.NextDouble() > tmp);  //reject; this happens about 1.5 times per deviate, on avg
             *  binomial = em;
             * }
             * if(_probability != probability)
             *  binomial = numberTrials - binomial;  // remember to undo the symmetry transformation
             * return binomial;
             * }
             *
             *
             *
             */
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets a list of random indices into an array, depending on various settings.
        /// </summary>
        /// <param name="numberOfLocationsToChooseFrom">The array length, indexes to which will be returned.</param>
        /// <param name="maximumNumberOfLocations">The maximum number of locations to select.</param>
        /// <param name="selectionWithReplacement"><see langword="true"/> if the same location can be returned more than once.</param>
        /// <param name="lambda">The probability of choosing a location at all.</param>
        /// <returns>A list of locations in the original array.</returns>
        public int[] GetLocations(
            int numberOfLocationsToChooseFrom,
            int maximumNumberOfLocations  = 1,
            bool selectionWithReplacement = false,
            double lambda = 0.1)
        {
            if (maximumNumberOfLocations <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maximumNumberOfLocations),
                                                      "Maximum number of locations must be greater than 0.");
            }

            if (!selectionWithReplacement && maximumNumberOfLocations > numberOfLocationsToChooseFrom)
            {
                throw new ArgumentOutOfRangeException(nameof(maximumNumberOfLocations),
                                                      "If sampling without replacement, cannot ask for more locations than are available.");
            }

            if (lambda < 0 || lambda > 1)
            {
                throw  new ArgumentOutOfRangeException(nameof(lambda),
                                                       "The probability of selecting a location must be between 0 and 1.");
            }

            if (lambda == 0)
            {
                return(new int[0]);
            }

            if (lambda == 1 && !selectionWithReplacement)
            {
                // There's a fast function implemented for this...
                return(Enumerable.Range(0, numberOfLocationsToChooseFrom)
                       .SelectCombination(maximumNumberOfLocations, Rng)
                       .ToArray());
            }

            var locations = new List <int>();
            var i         = 0;

            while (i < maximumNumberOfLocations)
            {
                // See if we will make a selection
                var mutate = Rng.NextDouble() < lambda;

                if (mutate)
                {
                    // See if we need to reduce the randomisation space
                    var offset = selectionWithReplacement
                        ? 0
                        : locations.Count;

                    // Generate a value
                    var location = Rng.Next(0, numberOfLocationsToChooseFrom - offset);

                    if (selectionWithReplacement)
                    {
                        // We are generating with replacement - just add to list.
                        locations.Add(location);
                    }
                    else
                    {
                        // Find the true value which the truncated space refers to
                        while (locations.Contains(location))
                        {
                            location++;
                        }
                        // Add to list
                        locations.Add(location);
                    }
                }

                i++;
            }

            return(locations.ToArray());
        }
 NextDouble()
 {
     return(_location + (_scale * Trig.Tangent(Constants.Pi * (RandomSource.NextDouble() - 0.5))));
 }
 NextDouble()
 {
     return(_a + (RandomSource.NextDouble() * _diff));
 }
 NextDouble()
 {
     return(_location / Math.Pow(1.0 - RandomSource.NextDouble(), _helper1));
 }
Exemplo n.º 24
0
 /// <summary>
 /// Implements random number generation for this variable
 /// </summary>
 /// <returns>A legal value (double).</returns>
 public object GetNextRandom(RandomSource rng)
 {
     return((rng.NextDouble()
             * (upperBoundForGeneration - lowerBoundForGeneration))
            + lowerBoundForGeneration);
 }
Exemplo n.º 25
0
 public static double Get(this RangeDouble d, RandomSource rand)
 {
     return(rand.NextDouble(d.Max - d.Min) + d.Min);
 }
        NextDouble()
        {
            double rand = 0.5 - RandomSource.NextDouble();

            return(_location - (_scale * Math.Sign(rand) * Math.Log(2.0 * Math.Abs(rand))));
        }