/// <summary> /// Creates an instance. /// </summary> /// <param name="mu"> The location parameter </param> /// <param name="b"> The scale parameter, greater than zero </param> /// <param name="engine"> A uniform random number generator, not null </param> public LaplaceDistribution(double mu, double b, RandomEngine engine) { ArgChecker.isTrue(b > 0, "b must be > 0"); ArgChecker.notNull(engine, "engine"); _mu = mu; _b = b; _engine = engine; }
/// <param name="mean"> The mean of the distribution </param> /// <param name="standardDeviation"> The standard deviation of the distribution, not negative or zero </param> /// <param name="randomEngine"> A generator of uniform random numbers, not null </param> public NormalDistribution(double mean, double standardDeviation, RandomEngine randomEngine) { ArgChecker.isTrue(standardDeviation > 0, "standard deviation"); ArgChecker.notNull(randomEngine, "randomEngine"); _mean = mean; _standardDeviation = standardDeviation; _normal = new Normal(mean, standardDeviation, randomEngine); }
/// <param name="degFreedom"> The number of degrees of freedom, not negative or zero </param> /// <param name="engine"> A generator of uniform random numbers, not null </param> public StudentTDistribution(double degFreedom, RandomEngine engine) { ArgChecker.isTrue(degFreedom > 0, "degrees of freedom"); ArgChecker.notNull(engine, "engine"); _degFreedom = degFreedom; _dist = new StudentT(degFreedom, engine); _beta = new InverseIncompleteBetaFunction(degFreedom / 2.0, 0.5); }
/// <param name="k"> The shape parameter of the distribution, not negative or zero </param> /// <param name="theta"> The scale parameter of the distribution, not negative or zero </param> /// <param name="engine"> A uniform random number generator, not null </param> public GammaDistribution(double k, double theta, RandomEngine engine) { ArgChecker.isTrue(k > 0, "k must be > 0"); ArgChecker.isTrue(theta > 0, "theta must be > 0"); ArgChecker.notNull(engine, "engine"); _gamma = new Gamma(k, 1.0 / theta, engine); _k = k; _theta = theta; }
protected virtual double[] MutateStrategy(double[] stddevs) { double[] child_stddevs = new double[stddevs.Length]; for (int i = 0; i < stddevs.Length; ++i) { child_stddevs[i] = stddevs[i] + RandomEngine.Gauss(0, System.Math.Sqrt(System.Math.Abs(stddevs[i]))); } return(child_stddevs); }
public ContinuousSolution[] Recombine(ContinuousSolution[] subset, object constraints) { ContinuousSolution a = subset[0]; ContinuousSolution b = subset[1]; ContinuousSolution d = (a - b) / 2; double[] lower_bounds = null; double[] upper_bounds = null; if (mLowerBounds == null || mUpperBounds == null) { if (constraints != null && constraints is Tuple <double[], double[]> ) { Tuple <double[], double[]> bounds = constraints as Tuple <double[], double[]>; lower_bounds = bounds.Item1; upper_bounds = bounds.Item2; } else { throw new InvalidCastException(); } } else { lower_bounds = mLowerBounds; upper_bounds = mUpperBounds; } if (lower_bounds.Length < d.Length) { throw new IndexOutOfRangeException(); } if (upper_bounds.Length < d.Length) { throw new IndexOutOfRangeException(); } ContinuousSolution[] children = new ContinuousSolution[subset.Length]; for (int i = 0; i < subset.Length; ++i) { double[] x = new double[d.Length]; for (int j = 0; j < d.Length; ++j) { int direction = RandomEngine.NextDouble() < 0.5 ? 1 : -1; double r = RandomEngine.NextDouble(); x[j] = subset[i][j] + d[j] * direction * r; x[j] = System.Math.Max(lower_bounds[j], x[j]); x[j] = System.Math.Min(upper_bounds[j], x[j]); } children[i] = new ContinuousSolution(x, double.MaxValue); } return(children); }
/// <summary> /// Chooses exactly one random element from successive blocks of <i>weight</i> input elements each. /// For example, if weight==2, and the input is 5*2=10 elements long, then chooses 5 random elements from the 10 elements such that /// one is chosen from the first block, one from the second, ..d, one from the last block. /// weight == 1.0 --> all elements are consumed (sampled)d 10.0 --> Consumes one random element from successive blocks of 10 elements eachd Etc. /// </summary> /// <param name="weight"></param> /// <param name="randomGenerator"></param> public WeightedRandomSampler(int weight, RandomEngine randomGenerator) { if (randomGenerator == null) { randomGenerator = Cern.Jet.Random.AbstractDistribution.MakeDefaultGenerator(); } this.generator = new Uniform(randomGenerator); Weight = weight; }
/// <summary> /// Creates an instance. /// </summary> /// <param name="mu"> The location parameter </param> /// <param name="sigma"> The scale parameter </param> /// <param name="ksi"> The shape parameter </param> /// <param name="engine"> A uniform random number generator, not null </param> public GeneralizedParetoDistribution(double mu, double sigma, double ksi, RandomEngine engine) { ArgChecker.isTrue(sigma > 0, "sigma must be > 0"); ArgChecker.isTrue(!DoubleMath.fuzzyEquals(ksi, 0d, 1e-15), "ksi cannot be zero"); ArgChecker.notNull(engine, "engine"); _mu = mu; _sigma = sigma; _ksi = ksi; _engine = engine; }
public StochasticHillClimber(double[] masks, CreateRandomNeighborhoodMethod generator = null) { mMasks = (double[])masks.Clone(); mSolutionGenerator = generator; if (mSolutionGenerator == null) { mSolutionGenerator = (x, index, constraints) => { double[] lower_bounds = null; double[] upper_bounds = null; if (mLowerBounds == null || mUpperBounds == null) { Tuple <double[], double[]> bounds = null; if (constraints is Tuple <double[], double[]> ) { bounds = constraints as Tuple <double[], double[]>; } else { throw new InvalidCastException(); } lower_bounds = bounds.Item1; upper_bounds = bounds.Item2; } else { lower_bounds = mLowerBounds; upper_bounds = mUpperBounds; } if (lower_bounds.Length < x.Length) { throw new ArgumentOutOfRangeException(); } if (upper_bounds.Length < x.Length) { throw new ArgumentOutOfRangeException(); } double[] x_p = (double[])x.Clone(); for (int i = 0; i < mMasks.Length; ++i) { int mindex = (index + i) % x_p.Length; double new_val = mMasks[i] > 0 ? x[(index + i)] + RandomEngine.Gauss(0, mMasks[i]) : x[(index + i) % x.Length]; new_val = System.Math.Max(lower_bounds[mindex], new_val); new_val = System.Math.Min(upper_bounds[mindex], new_val); x_p[mindex] = new_val; } return(x_p); }; } }
/// <summary> /// Constructs a random sampler that samples <tt>n</tt> random elements from an input sequence of <tt>N</tt> elements. /// </summary> /// <param name="n">the total number of elements to choose (must be >= 0).</param> /// <param name="N">number of elements to choose from (must be >= n).</param> /// <param name="randomGenerator">a random number generator. Set this parameter to <tt>null</tt> to use the default random number generator.</param> public RandomSamplingAssistant(long n, long N, RandomEngine randomGenerator) { this.n = n; this.sampler = new RandomSampler(n, N, 0, randomGenerator); this.buffer = new long[(int)System.Math.Min(n, MAX_BUFFER_SIZE)]; if (n > 0) { this.buffer[0] = -1; // start with the right offset } FetchNextBlock(); }
private void Initialization() { NumberOfGenerators = 20; NumberOfSamplingPoints = 10000; SelectedSamplingMethod = RandomEngine.HALTONSEQUENCE; SamplingMethods.Clear(); foreach (var item in Enum.GetNames(typeof(RandomEngine))) { SamplingMethods.Add(item); } }
protected virtual void Awake() { animator = GetComponent <Animator> (); boxCollider = GetComponent <BoxCollider2D> (); durability = GetComponent <Durability> (); randomEngine = new RandomEngine(); rigidBody = GetComponent <Rigidbody2D> (); spriteRenderer = GetComponent <SpriteRenderer> (); lastTime = Time.time; }
protected virtual double[] MutateStrategy(double[] stddevs) { double tau = 1.0 / System.Math.Sqrt(2.0 * stddevs.Length); double tau_p = 1.0 / System.Math.Sqrt(2.0 * System.Math.Sqrt(stddevs.Length)); double[] child_stddevs = new double[stddevs.Length]; for (int i = 0; i < stddevs.Length; ++i) { child_stddevs[i] = stddevs[i] * System.Math.Exp(RandomEngine.Gauss(0, tau_p) + RandomEngine.Gauss(0, tau)); } return(child_stddevs); }
/// <summary> /// Returns a random number from the Burr III, IV, V, VI, IX, XII distributions. /// <p> /// <b>Implementation:</b> Inversion method. /// This is a port of <i>burr2.c</i> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library. /// C-RAND's implementation, in turn, is based upon /// <p> /// Ld Devroye (1986): Non-Uniform Random Variate Generation, Springer Verlag, New Yorkd /// <p> /// </summary> /// <param name="r">must be > 0.</param> /// <param name="k">must be > 0.</param> /// <param name="nr">the number of the burr distribution (e.gd 3,4,5,6,9,12).</param> /// <param name="randomGenerator"></param> /// <returns></returns> public static double NextBurr2(double r, double k, int nr, RandomEngine randomGenerator) { /****************************************************************** * * * Burr III, IV, V, VI, IX, XII Distribution - Inversion * * * ****************************************************************** * * * FUNCTION : - burr2 samples a random number from one of the * * Burr III, IV, V, VI, IX, XII distributions with * * parameters r > 0 and k > 0, where the nod of * * the distribution is indicated by a pointer * * variabled * * REFERENCE : - Ld Devroye (1986): Non-Uniform Random Variate * * Generation, Springer Verlag, New Yorkd * * SUBPROGRAM : - drand(seed) ..d (0,1)-Uniform generator with * * unsigned long int *seedd * * * ******************************************************************/ double y, u; u = randomGenerator.Raw(); // U(0/1) y = System.Math.Exp(-System.Math.Log(u) / r) - 1.0; // u^(-1/r) - 1 switch (nr) { case 3: // BURR III return(System.Math.Exp(-System.Math.Log(y) / k)); // y^(-1/k) case 4: // BURR IV y = System.Math.Exp(k * System.Math.Log(y)) + 1.0; // y^k + 1 y = k / y; return(y); case 5: // BURR V y = System.Math.Atan(-System.Math.Log(y / k)); // arctan[log(y/k)] return(y); case 6: // BURR VI y = -System.Math.Log(y / k) / r; y = System.Math.Log(y + System.Math.Sqrt(y * y + 1.0)); return(y); case 9: // BURR IX y = 1.0 + 2.0 * u / (k * (1.0 - u)); y = System.Math.Exp(System.Math.Log(y) / r) - 1.0; // y^(1/r) -1 return(System.Math.Log(y)); case 12: // BURR XII return(System.Math.Exp(System.Math.Log(y) / k)); // y^(1/k) } return(0); }
public AdaptiveRandomSearch(int search_space_size, CreateNeighborMethod generator) { mSearchSpaceSize = search_space_size; mSolutionGenerator = generator; if (mSolutionGenerator == null) { mSolutionGenerator = (x, step_size, constraints) => { double[] lower_bounds = null; double[] upper_bounds = null; if (mLowerBounds == null || mUpperBounds == null) { if (constraints is Tuple <double[], double[]> ) { Tuple <double[], double[]> bounds = constraints as Tuple <double[], double[]>; lower_bounds = bounds.Item1; upper_bounds = bounds.Item2; } else { throw new InvalidCastException(); } } else { lower_bounds = mLowerBounds; upper_bounds = mUpperBounds; } if (lower_bounds.Length < x.Length) { throw new ArgumentOutOfRangeException(); } if (upper_bounds.Length < x.Length) { throw new ArgumentOutOfRangeException(); } for (int i = 0; i < x.Length; ++i) { // must check boundary ... double min = System.Math.Max(lower_bounds[i], x[i] - step_size); double max = System.Math.Min(upper_bounds[i], x[i] + step_size); double new_val = min + (max - min) * RandomEngine.NextDouble(); x[i] = new_val; } return(x); }; } }
public void Verify_Different_Randoms_Are_Created() { // Arrange var rnd1 = new RandomEngine(); var rnd2 = new RandomEngine(); // Act var value1 = rnd1.Next(); var value2 = rnd2.Next(); // Assert Assert.NotEqual(value1, value2); }
protected virtual ContinuousSolution MutateVector(ContinuousSolution solution, double[] lower_bounds, double[] upper_bounds, object constraints) { double[] x = new double[mDimension]; double[] strategy = solution.GetMutationStrategy(); for (int i = 0; i < mDimension; ++i) { x[i] = solution[i] + RandomEngine.Gauss(0, strategy[i]); x[i] = System.Math.Max(lower_bounds[i], x[i]); x[i] = System.Math.Min(upper_bounds[i], x[i]); } return(new ContinuousSolution(x, double.MaxValue)); }
protected virtual ContinuousSolution Recombine(ContinuousSolution[] pop, double[] lower_bounds, double[] upper_bounds, object constraints) { ContinuousSolution[] parents = new ContinuousSolution[mSelectedParentCount_rho]; for (int i = 0; i < mSelectedParentCount_rho; ++i) { parents[i] = BinaryTournamentSelection(pop); } HashSet <int> intersection_points = new HashSet <int>(); for (int i = 0; i < mSelectedParentCount_rho - 1; ++i) { int index = RandomEngine.NextInt(mDimension); while (intersection_points.Contains(index)) { index = RandomEngine.NextInt(mDimension); } intersection_points.Add(index); } int[] intersect_pts = intersection_points.OrderBy(s => s).ToArray(); int start_pt = 0; double[] x = new double[mDimension]; double[] child_strategy = new double[mDimension]; double[] parent_strategy = null; for (int i = 0; i < intersect_pts.Length; ++i) { int end_pt = intersect_pts[i]; parent_strategy = parents[i].GetMutationStrategy(); for (int j = start_pt; j < end_pt; ++j) { x[j] = parents[i][j]; child_strategy[j] = parent_strategy[j]; } } parent_strategy = parents[mSelectedParentCount_rho - 1].GetMutationStrategy(); for (int i = start_pt; i < mDimension; ++i) { x[i] = parents[mSelectedParentCount_rho - 1][i]; child_strategy[i] = parent_strategy[i]; } ContinuousSolution child = new ContinuousSolution(x, double.MaxValue); child.SetMutationStrategy(child_strategy); return(child); }
public static IRandom2D Create(RandomEngine randomEngine) { switch (randomEngine) { case RandomEngine.HALTONSEQUENCE: return(new HaltonSequence2D()); case RandomEngine.UNIFORMDISTRIBUTION: return(new UniformDistribution2D()); default: throw new ArgumentException("You should never received this exception (RandomEngineFactory)"); } }
/// <summary> /// Returns a random number from the distribution; bypasses the internal state. /// </summary> /// <param name="theMean"></param> /// <returns></returns> private int NextInt(double theMean) { /* * Adapted from "Numerical Recipes in C". */ double xm = theMean; double g = this.cached_g; if (xm == -1.0) { return(0); // not defined } if (xm < SWITCH_MEAN) { int poisson = -1; double product = 1; do { poisson++; product *= RandomGenerator.Raw(); } while (product >= g); // bug in CLHEP 1.4.0: was "} while ( product > g );" return(poisson); } else if (xm < MEAN_MAX) { double t; double em; double sq = this.cached_sq; double alxm = this.cached_alxm; RandomEngine rand = this.RandomGenerator; do { double y; do { y = System.Math.Tan(System.Math.PI * rand.Raw()); em = sq * y + xm; } while (em < 0.0); em = (double)(int)(em); // faster than em = System.Math.Floor(em); (em>=0.0) t = 0.9 * (1.0 + y * y) * System.Math.Exp(em * alxm - LogGamma(em + 1.0) - g); } while (rand.Raw() > t); return((int)em); } else { // mean is too large return((int)xm); } }
public void GenerateMoveForComplexGame() { var board = EngineTests.GenerateComplexGame(); var engine = new RandomEngine(); var generatedMove = engine.GenerateMove(board.Clone()); this.TestContext.WriteLine(generatedMove.ToString()); this.TestContext.WriteLine("Evaluations: " + engine.Evaluations.ToString(CultureInfo.CurrentCulture)); this.TestContext.WriteLine("Visitations: " + engine.Visitations.ToString(CultureInfo.CurrentCulture)); board.MovePiece(generatedMove); }
/// <summary> /// Returns a Laplace (Double Exponential) distributed random number from the standard Laplace distribution L(0,1)d /// <p> /// <b>Implementation:</b> Inversion method. /// This is a port of <i>lapin.c</i> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library. /// <p> /// </summary> /// <param name="randomGenerator"></param> /// <returns>a number in the open unit interval <code>(0.0,1.0)</code> (excluding 0.0 and 1.0).</returns> public static double NextLaplace(RandomEngine randomGenerator) { double u = randomGenerator.Raw(); u = u + u - 1.0; if (u > 0) { return(-System.Math.Log(1.0 - u)); } else { return(System.Math.Log(1.0 + u)); } }
public virtual void RandomSearch(double[] lower_bounds, double[] upper_bounds, object constraints) //initialize random solution { double lower_bound; double upper_bound; double range; for (int d = 0; d < mData.Length; ++d) { lower_bound = lower_bounds[d]; upper_bound = upper_bounds[d]; range = upper_bound - lower_bound; mData[d] = lower_bound + range * RandomEngine.NextDouble(); } this.UpdateCost(); }
/// <summary> /// Returns an erlang distributed random number with the given variance and mean. /// </summary> /// <param name="variance"></param> /// <param name="mean"></param> /// <param name="randomGenerator"></param> /// <returns></returns> public static double NextErlang(double variance, double mean, RandomEngine randomGenerator) { int k = (int)((mean * mean) / variance + 0.5); k = (k > 0) ? k : 1; double a = k / mean; double prod = 1.0; for (int i = 0; i < k; i++) { prod *= randomGenerator.Raw(); } return(-System.Math.Log(prod) / a); }
public static void UseGoodEngine() { var goodEngine = new RandomEngine(); var board = new Board(); Assert.AreEqual(Player.X, board.CurrentPlayer, "The starting player is invalid."); board.MovePiece(new Point(0, 0), new Point(0, 4)); Assert.AreEqual(Player.O, board.CurrentPlayer, "The player before the generated move is invalid."); var engineMove = goodEngine.GenerateMove(board, new ManualResetEvent(false)); Assert.AreEqual(Player.O, engineMove.Player, "The player after the generated move is invalid."); board.MovePiece(engineMove.Source, engineMove.Destination); Assert.AreEqual(Player.X, board.CurrentPlayer, "The player after the generated move was performed is invalid."); }
protected ContinuousSolution BinaryTournamentSelection(ContinuousSolution[] pop) { int index1 = RandomEngine.NextInt(pop.Length); int index2 = index1; do { index2 = RandomEngine.NextInt(pop.Length); } while (index1 == index2); if (pop[index1].Cost < pop[index2].Cost) { return(pop[index1]); } return(pop[index2]); }
public static void Shuffle <T>(this List <T> list) { if (list.Count == 0) { return; } int index = 0; while (index < list.Count - 1) { int index2 = RandomEngine.NextInt(list.Count - index) + index; index2 = index2 % list.Count; T temp = list[index]; list[index] = list[index2]; list[index] = temp; } }
/// <summary> /// Returns a lambda distributed random number with parameters l3 and l4. /// <p> /// <b>Implementation:</b> Inversion method. /// This is a port of <i>lamin.c</i> from the <A HREF="http://www.cis.tu-graz.ac.at/stat/stadl/random.html">C-RAND / WIN-RAND</A> library. /// C-RAND's implementation, in turn, is based upon /// <p> /// J.Sd Ramberg, B:Wd Schmeiser (1974): An approximate method for generating asymmetric variables, Communications ACM 17, 78-82. /// <p> /// </summary> /// <param name="l3"></param> /// <param name="l4"></param> /// <param name="randomGenerator"></param> /// <returns></returns> public static double NextLambda(double l3, double l4, RandomEngine randomGenerator) { double l_sign; if ((l3 < 0) || (l4 < 0)) { l_sign = -1.0; // sign(l) } else { l_sign = 1.0; } double u = randomGenerator.Raw(); // U(0/1) double x = l_sign * (System.Math.Exp(System.Math.Log(u) * l3) - System.Math.Exp(System.Math.Log(1.0 - u) * l4)); return(x); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var table = new Table(8, 8); table.Reset(); RandomEngine randomEngine = new RandomEngine(); Console.Write(table.ToString()); Console.ReadLine(); StringBuilder pgn = new StringBuilder(); int i = 1; while (table.CanMove(PieceColor.White) && table.CanMove(PieceColor.Black)) { Console.WriteLine("Thinking..."); var whiteMove = GameEngine.NextMove(table, PieceColor.White, 3); if (whiteMove != null) { Console.WriteLine("White: " + whiteMove.ToString()); table.Move(whiteMove); pgn.Append(i.ToString() + ". "); pgn.Append(whiteMove.ToString() + " "); Console.Write(table.ToString()); //var blackMove = GameEngine.NextMove(table, PieceColor.Black, 2); var blackMove = randomEngine.NextMove(table, PieceColor.Black); if (blackMove != null) { Console.WriteLine("Black: " + blackMove.ToString()); table.Move(blackMove); pgn.Append(blackMove.ToString() + " "); i++; Console.Write(table.ToString()); } } //Console.ReadLine(); } Console.WriteLine("*** End of game ***"); Console.WriteLine(pgn.ToString()); }
private static void DisturbPoints(RandomEngine random, double scale, IList <Point> points, IList <Vector> normals) { var count = points.Count; for (var i = 1; i < count; i++) { var num3 = random.NextGaussian(0.0, 1.0 * scale); var num4 = random.NextUniform(-0.5, 0.5) * scale; var point = points[i]; var vector = normals[i]; var vector2 = normals[i]; var point2 = points[i]; var vector3 = normals[i]; var vector4 = normals[i]; points[i] = new Point(point.X + vector.X * num4 - vector2.Y * num3, point2.Y + vector3.X * num3 + vector4.Y * num4); } }