本文整理汇总了C#中MersenneTwister.Next方法的典型用法代码示例。如果您正苦于以下问题:C# MersenneTwister.Next方法的具体用法?C# MersenneTwister.Next怎么用?C# MersenneTwister.Next使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MersenneTwister
的用法示例。
在下文中一共展示了MersenneTwister.Next方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GenerateUrlCompatibleName
public static string GenerateUrlCompatibleName(int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException("The length parameter " + "cannot be below zero!");
}
var seed = (uint)(Guid.NewGuid().GetHashCode() + (uint)Int32.MaxValue);
var result = new StringBuilder(length);
var twister = new MersenneTwister(seed);
for (int i = 0; i < length; ++i)
{
result.Append(
(char)twister.Next(Constants.BasicLatinStartSymbolNumber, Constants.BasicLatinEndSymbolNumber));
}
for (int i = Constants.BasicLatinExcludedStartSymbolNumber;
i <= Constants.BasicLatinExcludedEndSymbolNumber;
++i)
{
result.Replace(
(char)i,
(char)
twister.Next(Constants.BasicLatinStartDigitSymbolNumber, Constants.BasicLatinEndDigitSymbolNumber));
}
return result.ToString();
}
示例2: RandomWalk
static IEnumerable<CPos> RandomWalk(CPos p, MersenneTwister r)
{
for (;;)
{
var dx = r.Next(-1, 2);
var dy = r.Next(-1, 2);
if (dx == 0 && dy == 0)
continue;
p += new CVec(dx, dy);
yield return p;
}
}
示例3: OnEnter
// Code that runs on entering the state.
public override void OnEnter()
{
MersenneTwister random = new MersenneTwister();
storeResult.Value = random.Next(max.Value);
Finish();
}
示例4: DrunkardWalk
public static int DrunkardWalk(Unit unit)
{
MersenneTwister mt = new MersenneTwister();
unit.MakeAMove((CardinalDirection)mt.Next(9));
return 100;
}
示例5: MyClassInitialize
public static void MyClassInitialize(TestContext testContext) {
random = new MersenneTwister();
coordinates = new DoubleMatrix(ProblemSize, 2);
distances = new DistanceMatrix(ProblemSize, ProblemSize);
for (int i = 0; i < ProblemSize; i++) {
coordinates[i, 0] = random.Next(ProblemSize * 10);
coordinates[i, 1] = random.Next(ProblemSize * 10);
}
for (int i = 0; i < ProblemSize - 1; i++) {
for (int j = i + 1; j < ProblemSize; j++) {
distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2)));
distances[j, i] = distances[i, j];
}
}
tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random);
}
示例6: InitTree
public static void InitTree(ISymbolicExpressionTree tree, MersenneTwister twister, List<string> varNames) {
foreach (var node in tree.IterateNodesPostfix()) {
if (node is VariableTreeNode) {
var varNode = node as VariableTreeNode;
varNode.Weight = twister.NextDouble() * 20.0 - 10.0;
varNode.VariableName = varNames[twister.Next(varNames.Count)];
} else if (node is ConstantTreeNode) {
var constantNode = node as ConstantTreeNode;
constantNode.Value = twister.NextDouble() * 20.0 - 10.0;
}
}
}
示例7: Start
// Use this for initialization
void Start () {
rand = new MersenneTwister ();
if(player.RoomsTotal == 0) {
roomsTotal = rand.Next (NUM_ROOMS_MIN, NUM_ROOMS_MAX);
player.RoomsTotal = roomsTotal;
labelRoomClear.text = "0 / " + roomsTotal.ToString ();
} else {
roomsTotal = player.RoomsTotal;
roomsCleared = player.RoomsLeft;
labelRoomClear.text = roomsCleared.ToString () + " / " + roomsTotal.ToString ();
}
}
示例8: MyClassInitialize
public static void MyClassInitialize(TestContext testContext) {
random = new MersenneTwister();
coordinates = new DoubleMatrix(ProblemSize, 2);
distances = new DistanceMatrix(ProblemSize, ProblemSize);
for (var i = 0; i < ProblemSize; i++) {
coordinates[i, 0] = random.Next(ProblemSize * 10);
coordinates[i, 1] = random.Next(ProblemSize * 10);
}
for (var i = 0; i < ProblemSize - 1; i++) {
for (var j = i + 1; j < ProblemSize; j++) {
distances[i, j] = Math.Round(Math.Sqrt(Math.Pow(coordinates[i, 0] - coordinates[j, 0], 2) + Math.Pow(coordinates[i, 1] - coordinates[j, 1], 2)));
distances[j, i] = distances[i, j];
}
}
probabilities = new DoubleArray(ProblemSize);
for (var i = 0; i < ProblemSize; i++) {
probabilities[i] = random.NextDouble();
}
realizations = new ItemList<BoolArray>(RealizationsSize);
for (var i = 0; i < RealizationsSize; i++) {
var countOnes = 0;
var newRealization = new BoolArray(ProblemSize);
while (countOnes < 4) { //only generate realizations with at least 4 cities visited
countOnes = 0;
for (var j = 0; j < ProblemSize; j++) {
newRealization[j] = random.NextDouble() < probabilities[j];
if (newRealization[j]) countOnes++;
}
}
realizations.Add(newRealization);
}
tour = new Permutation(PermutationTypes.RelativeUndirected, ProblemSize, random);
}
示例9: SubtreeCrossoverDistributionsTest
public void SubtreeCrossoverDistributionsTest() {
int generations = 5;
var trees = new List<ISymbolicExpressionTree>();
var grammar = Grammars.CreateArithmeticAndAdfGrammar();
var random = new MersenneTwister(31415);
double msPerCrossoverEvent;
for (int i = 0; i < POPULATION_SIZE; i++) {
trees.Add(ProbabilisticTreeCreator.Create(random, grammar, 100, 10));
for (int j = random.Next(3); j < 3; j++)
SubroutineCreater.CreateSubroutine(random, trees[i], 100, 10, 3, 3);
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int gCount = 0; gCount < generations; gCount++) {
for (int i = 0; i < POPULATION_SIZE; i++) {
var par0 = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone();
var par1 = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone();
SubtreeCrossover.Cross(random, par0, par1, 0.9, 100, 10);
}
}
stopwatch.Stop();
foreach (var tree in trees)
Util.IsValid(tree);
msPerCrossoverEvent = stopwatch.ElapsedMilliseconds / (double)POPULATION_SIZE / (double)generations;
Console.WriteLine("SubtreeCrossover: " + Environment.NewLine +
msPerCrossoverEvent + " ms per crossover event (~" + Math.Round(1000.0 / (msPerCrossoverEvent)) + "crossovers / s)" + Environment.NewLine +
Util.GetSizeDistributionString(trees, 105, 5) + Environment.NewLine +
Util.GetFunctionDistributionString(trees) + Environment.NewLine +
Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine +
Util.GetTerminalDistributionString(trees) + Environment.NewLine
);
//mkommend: commented due to performance issues on the builder
//Assert.IsTrue(Math.Round(1000.0 / (msPerCrossoverEvent)) > 2000); // must achieve more than 2000 x-overs/s
}
示例10: SubroutineDuplicaterDistributionsTest
public void SubroutineDuplicaterDistributionsTest() {
var trees = new List<ISymbolicExpressionTree>();
var grammar = Grammars.CreateArithmeticAndAdfGrammar();
var random = new MersenneTwister();
for (int i = 0; i < POPULATION_SIZE; i++) {
ISymbolicExpressionTree tree = null;
do {
tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
for (int j = random.Next(3); j < 3; j++)
SubroutineCreater.CreateSubroutine(random, tree, 100, 10, 3, 3);
} while (!HasOneAdf(tree));
var success = SubroutineDuplicater.DuplicateSubroutine(random, tree, 3, 3);
Assert.IsTrue(success);
Util.IsValid(tree);
trees.Add(tree);
}
Console.WriteLine("SubroutineDuplicater: " + Environment.NewLine +
Util.GetSizeDistributionString(trees, 105, 5) + Environment.NewLine +
Util.GetFunctionDistributionString(trees) + Environment.NewLine +
Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine +
Util.GetTerminalDistributionString(trees) + Environment.NewLine
);
}
示例11: CopmareRandomGeneratorsSpeed
private static void CopmareRandomGeneratorsSpeed()
{
var sw = new Stopwatch();
var maxCount = 10000000;
sw.Start();
var r1 = new Random();
for (int i = 0; i < maxCount; i++)
{
var x = r1.Next();
}
sw.Stop();
var time1 = sw.ElapsedMilliseconds;
sw.Restart();
var r2 = new MersenneTwister();
for (int i = 0; i < maxCount; i++)
{
var x = r2.Next();
}
sw.Stop();
var time2 = sw.ElapsedMilliseconds;
}
示例12: Run
protected override void Run(CancellationToken cancellationToken) {
// Set up the algorithm
if (SetSeedRandomly) Seed = new System.Random().Next();
var rand = new MersenneTwister((uint)Seed);
// Set up the results display
var iterations = new IntValue(0);
Results.Add(new Result("Iterations", iterations));
var table = new DataTable("Qualities");
table.Rows.Add(new DataRow("R² (train)"));
table.Rows.Add(new DataRow("R² (test)"));
Results.Add(new Result("Qualities", table));
var curLoss = new DoubleValue();
var curTestLoss = new DoubleValue();
Results.Add(new Result("R² (train)", curLoss));
Results.Add(new Result("R² (test)", curTestLoss));
var runCollection = new RunCollection();
if (StoreRuns)
Results.Add(new Result("Runs", runCollection));
// init
var problemData = Problem.ProblemData;
var targetVarName = problemData.TargetVariable;
var activeVariables = problemData.AllowedInputVariables.Concat(new string[] { problemData.TargetVariable });
var modifiableDataset = new ModifiableDataset(
activeVariables,
activeVariables.Select(v => problemData.Dataset.GetDoubleValues(v).ToList()));
var trainingRows = problemData.TrainingIndices;
var testRows = problemData.TestIndices;
var yPred = new double[trainingRows.Count()];
var yPredTest = new double[testRows.Count()];
var y = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
var curY = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices).ToArray();
var yTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray();
var curYTest = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TestIndices).ToArray();
var nu = Nu;
var mVars = (int)Math.Ceiling(M * problemData.AllowedInputVariables.Count());
var rRows = (int)Math.Ceiling(R * problemData.TrainingIndices.Count());
var alg = RegressionAlgorithm;
List<IRegressionModel> models = new List<IRegressionModel>();
try {
// Loop until iteration limit reached or canceled.
for (int i = 0; i < Iterations; i++) {
cancellationToken.ThrowIfCancellationRequested();
modifiableDataset.RemoveVariable(targetVarName);
modifiableDataset.AddVariable(targetVarName, curY.Concat(curYTest));
SampleTrainingData(rand, modifiableDataset, rRows, problemData.Dataset, curY, problemData.TargetVariable, problemData.TrainingIndices); // all training indices from the original problem data are allowed
var modifiableProblemData = new RegressionProblemData(modifiableDataset,
problemData.AllowedInputVariables.SampleRandomWithoutRepetition(rand, mVars),
problemData.TargetVariable);
modifiableProblemData.TrainingPartition.Start = 0;
modifiableProblemData.TrainingPartition.End = rRows;
modifiableProblemData.TestPartition.Start = problemData.TestPartition.Start;
modifiableProblemData.TestPartition.End = problemData.TestPartition.End;
if (!TrySetProblemData(alg, modifiableProblemData))
throw new NotSupportedException("The algorithm cannot be used with GBM.");
IRegressionModel model;
IRun run;
// try to find a model. The algorithm might fail to produce a model. In this case we just retry until the iterations are exhausted
if (TryExecute(alg, rand.Next(), RegressionAlgorithmResult, out model, out run)) {
int row = 0;
// update predictions for training and test
// update new targets (in the case of squared error loss we simply use negative residuals)
foreach (var pred in model.GetEstimatedValues(problemData.Dataset, trainingRows)) {
yPred[row] = yPred[row] + nu * pred;
curY[row] = y[row] - yPred[row];
row++;
}
row = 0;
foreach (var pred in model.GetEstimatedValues(problemData.Dataset, testRows)) {
yPredTest[row] = yPredTest[row] + nu * pred;
curYTest[row] = yTest[row] - yPredTest[row];
row++;
}
// determine quality
OnlineCalculatorError error;
var trainR = OnlinePearsonsRCalculator.Calculate(yPred, y, out error);
var testR = OnlinePearsonsRCalculator.Calculate(yPredTest, yTest, out error);
// iteration results
curLoss.Value = error == OnlineCalculatorError.None ? trainR * trainR : 0.0;
curTestLoss.Value = error == OnlineCalculatorError.None ? testR * testR : 0.0;
models.Add(model);
}
if (StoreRuns)
runCollection.Add(run);
table.Rows["R² (train)"].Values.Add(curLoss.Value);
//.........这里部分代码省略.........
示例13: RandomValidColor
public HSLColor RandomValidColor(MersenneTwister random, IEnumerable<Color> terrainColors, IEnumerable<Color> playerColors)
{
HSLColor color;
Color forbidden;
Action<string> ignoreError = _ => { };
do
{
var h = random.Next(255) / 255f;
var s = float2.Lerp(HsvSaturationRange[0], HsvSaturationRange[1], random.NextFloat());
var v = float2.Lerp(HsvValueRange[0], HsvValueRange[1], random.NextFloat());
color = HSLColor.FromHSV(h, s, v);
} while (!IsValid(color.RGB, out forbidden, terrainColors, playerColors, ignoreError));
return color;
}
示例14: ChooseRandomCell
public CPos ChooseRandomCell(MersenneTwister rand)
{
var x = rand.Next(Bounds.Left, Bounds.Right);
var y = rand.Next(Bounds.Top, Bounds.Bottom);
return MapToCell(TileShape, new CPos(x, y));
}
示例15: Main
public static void Main(string[] args)
{
bool showHelp = false;
int width = 500;
int height = 500;
var options = new OptionSet()
{
{
"?|help",
"show this message and exit",
v => showHelp = v != null
},
{
"w|width=",
"set level width",
v => width = v != null ? int.Parse(v) : width
},
{
"h|height=",
"set level height",
v => height = v != null ? int.Parse(v) : height
},
};
List<string> extras;
try
{
extras = options.Parse(args);
}
catch (OptionException e)
{
Console.Write("{0}: ", GetExecutableName());
Console.WriteLine(e.Message);
Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
return;
}
if (extras.Count < 0 || extras.Count > 1 || showHelp == true)
{
Console.WriteLine("Usage: {0} [OPTIONS]+ [output_map]", GetExecutableName());
Console.WriteLine();
Console.WriteLine("Options:");
options.WriteOptionDescriptions(Console.Out);
return;
}
var outputPath = extras.Count > 0 ? extras[0] : "space.map";
var templates = LoadEntities();
int cx = width / 2;
int cy = height / 2;
// ReSharper disable UnusedVariable
var radius = (int)(Math.Min(width, height) / 2.0);
// ReSharper restore UnusedVariable
var range = Math.Min(width, height) / 2.5;
var rng = new MersenneTwister();
var noise = PerlinNoise.Generate(
width, height, 0.0325f, 1.0f, 0.5f, 16, rng);
var physics = new bool[width,height];
var vision = new bool[width,height];
var entities = new List<Entity>();
for (int x = 8; x < width - 8; x++)
{
for (int y = 8; y < height - 8; y++)
{
var distance = GetDistance(cx, cy, x, y);
if (distance > range &&
rng.Next(100) > 2)
{
continue;
}
var magic = noise[x, y];
if (magic >= 200)
{
}
else if (magic >= 180)
{
if (rng.Next(100) >= 60 &&
(x % 2) == 0 &&
(y % 2) == 0)
{
var template = templates
.Where(t => t.Category == "asteroid")
.OrderBy(t => rng.Next())
.FirstOrDefault();
if (template != null &&
template.CanPlaceWithPhysics(x, y, physics, width, height) == true)
{
var entity = new Entity(x, y, template);
//.........这里部分代码省略.........