本文整理汇总了C#中MersenneTwister.NextDouble方法的典型用法代码示例。如果您正苦于以下问题:C# MersenneTwister.NextDouble方法的具体用法?C# MersenneTwister.NextDouble怎么用?C# MersenneTwister.NextDouble使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MersenneTwister
的用法示例。
在下文中一共展示了MersenneTwister.NextDouble方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SampleKnownValues
public void SampleKnownValues()
{
var mt = new MersenneTwister(0);
Assert.AreEqual(mt.NextDouble(), 0.5488135024320365);
Assert.AreEqual(mt.NextDouble(), 0.5928446165269344);
Assert.AreEqual(mt.NextDouble(), 0.7151893651381110);
Assert.AreEqual(mt.NextDouble(), 0.8442657442866512);
}
示例2: SampleKnownValues
public void SampleKnownValues()
{
var mt = new MersenneTwister(0);
Assert.AreEqual(mt.NextDouble(), 0.5488135023042560);
Assert.AreEqual(mt.NextDouble(), 0.5928446163889021);
Assert.AreEqual(mt.NextDouble(), 0.7151893649715930);
Assert.AreEqual(mt.NextDouble(), 0.8442657440900803);
}
示例3: 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;
}
}
}
示例4: Main
public override void Main() {
DateTime start = DateTime.UtcNow;
QuadraticAssignmentProblem qap;
if (vars.Contains("qap")) qap = vars.qap;
else {
var provider = new DreznerQAPInstanceProvider();
var instance = provider.GetDataDescriptors().Single(x => x.Name == "dre56");
var data = provider.LoadData(instance);
qap = new QuadraticAssignmentProblem();
qap.Load(data);
vars.qap = qap;
}
const uint seed = 0;
const int popSize = 100;
const int generations = 1000;
const double mutationRate = 0.05;
var random = new MersenneTwister(seed);
var population = new Permutation[popSize];
var qualities = new double[popSize];
var nextGen = new Permutation[popSize];
var nextQual = new double[popSize];
var qualityChart = new DataTable("Quality Chart");
var qualityRow = new DataRow("Best Quality");
qualityChart.Rows.Add(qualityRow);
vars.qualityChart = qualityChart;
for (int i = 0; i < popSize; i++) {
population[i] = new Permutation(PermutationTypes.Absolute, qap.Weights.Rows, random);
qualities[i] = QAPEvaluator.Apply(population[i], qap.Weights, qap.Distances);
}
var bestQuality = qualities.Min();
var bestQualityGeneration = 0;
for (int g = 0; g < generations; g++) {
var parents = population.SampleProportional(random, 2 * popSize, qualities, windowing: true, inverseProportional: true).ToArray();
for (int i = 0; i < popSize; i++) {
nextGen[i] = PartiallyMatchedCrossover.Apply(random, parents[i * 2], parents[i * 2 + 1]);
if (random.NextDouble() < mutationRate) Swap2Manipulator.Apply(random, nextGen[i]);
nextQual[i] = QAPEvaluator.Apply(nextGen[i], qap.Weights, qap.Distances);
if (nextQual[i] < bestQuality) {
bestQuality = nextQual[i];
bestQualityGeneration = g;
}
}
qualityRow.Values.Add(bestQuality);
Array.Copy(nextGen, population, popSize);
Array.Copy(nextQual, qualities, popSize);
}
vars.elapsed = new TimeSpanValue(DateTime.UtcNow - start);
vars.bestQuality = bestQuality;
vars.bestQualityFoundAt = bestQualityGeneration;
}
示例5: CreateRandomDataset
public static Dataset CreateRandomDataset(MersenneTwister twister, int rows, int columns) {
double[,] data = new double[rows, columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
data[i, j] = twister.NextDouble() * 2.0 - 1.0;
}
}
IEnumerable<string> variableNames = new string[] { "y" }.Concat(Enumerable.Range(0, columns - 1).Select(x => "x" + x.ToString()));
Dataset ds = new Dataset(variableNames, data);
return ds;
}
示例6: 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);
}
示例7: OverlayIdealGrid
//.........这里部分代码省略.........
{
// record the positions of the corners
corners.Add(grid[grid_tx, grid_ty]);
corners.Add(grid[grid_bx, grid_ty]);
corners.Add(grid[grid_bx, grid_by]);
corners.Add(grid[grid_tx, grid_by]);
double dx, dy;
double x0 = grid[grid_tx, grid_ty].x;
double y0 = grid[grid_tx, grid_ty].y;
double x1 = grid[grid_bx, grid_ty].x;
double y1 = grid[grid_bx, grid_ty].y;
double x2 = grid[grid_tx, grid_by].x;
double y2 = grid[grid_tx, grid_by].y;
double x3 = grid[grid_bx, grid_by].x;
double y3 = grid[grid_bx, grid_by].y;
polygon2D perimeter = new polygon2D();
perimeter.Add((float)x0, (float)y0);
perimeter.Add((float)x1, (float)y1);
perimeter.Add((float)x3, (float)y3);
perimeter.Add((float)x2, (float)y2);
int grid_width = grid_bx - grid_tx;
int grid_height = grid_by - grid_ty;
int min_hits = 0;
double min_dx = 0, min_dy = 0;
// try various perimeter sizes
double min_dist = double.MaxValue;
int max_perim_size_tries = 100;
polygon2D best_perimeter = perimeter;
MersenneTwister rnd = new MersenneTwister(random_seed);
for (int perim_size = 0; perim_size < max_perim_size_tries; perim_size++)
{
// try a small range of translations
for (int nudge_x = -10; nudge_x <= 10; nudge_x++)
{
for (int nudge_y = -5; nudge_y <= 5; nudge_y++)
{
// create a perimeter at this scale and translation
polygon2D temp_perimeter = perimeter.Scale(1.0f + (perim_size * 0.1f / max_perim_size_tries));
temp_perimeter = temp_perimeter.ScaleSideLength(0, 0.95f + ((float)rnd.NextDouble() * 0.1f));
temp_perimeter = temp_perimeter.ScaleSideLength(2, 0.95f + ((float)rnd.NextDouble() * 0.1f));
for (int i = 0; i < temp_perimeter.x_points.Count; i++)
{
temp_perimeter.x_points[i] += nudge_x;
temp_perimeter.y_points[i] += nudge_y;
}
// create a grid based upon the perimeter
grid2D temp_overlay_grid = new grid2D(grid_width, grid_height, temp_perimeter, 0, false);
// how closely does the grid fit the actual observations ?
double temp_min_dist = min_dist;
BestFit(grid_tx, grid_ty, grid,
temp_overlay_grid, ref min_dist,
ref min_dx, ref min_dy, ref min_hits,
ref grid_offset_x, ref grid_offset_y);
// record the closest fit
if (temp_min_dist < min_dist)
{
best_perimeter = temp_perimeter;
overlay_grid = temp_overlay_grid;
}
}
}
}
if (min_hits > 0)
{
dx = min_dx;
dy = min_dy;
Console.WriteLine("dx: " + dx.ToString());
Console.WriteLine("dy: " + dy.ToString());
x0 += dx;
y0 += dy;
x1 += dx;
y1 += dy;
x2 += dx;
y2 += dy;
x3 += dx;
y3 += dy;
perimeter = new polygon2D();
perimeter.Add((float)x0, (float)y0);
perimeter.Add((float)x1, (float)y1);
perimeter.Add((float)x3, (float)y3);
perimeter.Add((float)x2, (float)y2);
overlay_grid = new grid2D(grid_width, grid_height, perimeter, 0, false);
}
}
return (overlay_grid);
}
示例8: FitCurve
/// <summary>
/// fits a curve to the given grid using the given centre of distortion
/// </summary>
/// <param name="grid">detected grid dots</param>
/// <param name="overlay_grid">overlayed ideal rectified grid</param>
/// <param name="centre_of_distortion">centre of lens distortion</param>
/// <param name="curve">curve to be fitted</param>
private static void FitCurve(calibrationDot[,] grid,
grid2D overlay_grid,
calibrationDot centre_of_distortion,
polynomial curve,
double noise, MersenneTwister rnd,
int grid_offset_x, int grid_offset_y)
{
double[] prev_col = new double[grid.GetLength(1) * 2];
double[] col = new double[prev_col.Length];
double half_noise = noise / 2;
double rectified_x, rectified_y;
for (int pass = 0; pass < 1; pass++)
{
// for every detected dot
for (int grid_x = 0; grid_x < grid.GetLength(0); grid_x++)
{
double prev_rectified_radial_dist = 0;
double prev_actual_radial_dist = 0;
int prev_grid_y = -1;
for (int grid_y = 0; grid_y < grid.GetLength(1); grid_y++)
{
if (grid[grid_x, grid_y] != null)
{
if ((grid_x + grid_offset_x < overlay_grid.line_intercepts.GetLength(0)) &&
(grid_y + grid_offset_y < overlay_grid.line_intercepts.GetLength(1)) &&
(grid_x + grid_offset_x >= 0) && (grid_y + grid_offset_y >= 0))
{
// find the rectified distance of the dot from the centre of distortion
rectified_x = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 0];
rectified_y = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 1];
if (pass > 0)
{
rectified_x += (((rnd.NextDouble() * noise) - half_noise) * 0.1);
rectified_y += (((rnd.NextDouble() * noise) - half_noise) * 0.1);
}
//double rectified_x = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 0];
//double rectified_y = overlay_grid.line_intercepts[grid_x + grid_offset_x, grid_y + grid_offset_y, 1];
double rectified_dx = rectified_x - centre_of_distortion.x;
double rectified_dy = rectified_y - centre_of_distortion.y;
double rectified_radial_dist = Math.Sqrt(rectified_dx * rectified_dx + rectified_dy * rectified_dy);
// find the actual raw image distance of the dot from the centre of distortion
//double actual_x = grid[grid_x, grid_y].x + (((rnd.NextDouble() * noise) - half_noise) * 2);
//double actual_y = grid[grid_x, grid_y].y + (((rnd.NextDouble() * noise) - half_noise) * 2);
double actual_x = grid[grid_x, grid_y].x;
double actual_y = grid[grid_x, grid_y].y;
double actual_dx = actual_x - centre_of_distortion.x;
double actual_dy = actual_y - centre_of_distortion.y;
double actual_radial_dist = Math.Sqrt(actual_dx * actual_dx + actual_dy * actual_dy);
// plot
curve.AddPoint(rectified_radial_dist, actual_radial_dist);
col[(grid_y * 2)] = rectified_radial_dist;
col[(grid_y * 2) + 1] = actual_radial_dist;
prev_rectified_radial_dist = rectified_radial_dist;
prev_actual_radial_dist = actual_radial_dist;
prev_grid_y = grid_y;
}
}
}
for (int i = 0; i < col.Length; i++)
prev_col[i] = col[i];
}
}
// find the best fit curve
curve.Solve();
}
示例9: AllArchitectureAlteringOperatorsDistributionTest
public void AllArchitectureAlteringOperatorsDistributionTest() {
var trees = new List<ISymbolicExpressionTree>();
var newTrees = new List<ISymbolicExpressionTree>();
var grammar = Grammars.CreateArithmeticAndAdfGrammar();
var random = new MersenneTwister(31415);
SymbolicExpressionTreeStringFormatter formatter = new SymbolicExpressionTreeStringFormatter();
IntValue maxTreeSize = new IntValue(MAX_TREE_LENGTH);
IntValue maxTreeHeigth = new IntValue(MAX_TREE_DEPTH);
IntValue maxDefuns = new IntValue(3);
IntValue maxArgs = new IntValue(3);
for (int i = 0; i < POPULATION_SIZE; i++) {
var tree = ProbabilisticTreeCreator.Create(random, grammar, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
Util.IsValid(tree);
trees.Add(tree);
}
Stopwatch stopwatch = new Stopwatch();
int failedEvents = 0;
for (int g = 0; g < N_ITERATIONS; g++) {
for (int i = 0; i < POPULATION_SIZE; i++) {
if (random.NextDouble() < 0.5) {
// manipulate
stopwatch.Start();
var selectedTree = (ISymbolicExpressionTree)trees.SampleRandom(random).Clone();
var oldTree = (ISymbolicExpressionTree)selectedTree.Clone();
bool success = false;
int sw = random.Next(6);
switch (sw) {
case 0: success = ArgumentCreater.CreateNewArgument(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break;
case 1: success = ArgumentDeleter.DeleteArgument(random, selectedTree, 3, 3); break;
case 2: success = ArgumentDuplicater.DuplicateArgument(random, selectedTree, 3, 3); break;
case 3: success = SubroutineCreater.CreateSubroutine(random, selectedTree, MAX_TREE_LENGTH, MAX_TREE_DEPTH, 3, 3); break;
case 4: success = SubroutineDuplicater.DuplicateSubroutine(random, selectedTree, 3, 3); break;
case 5: success = SubroutineDeleter.DeleteSubroutine(random, selectedTree, 3, 3); break;
}
stopwatch.Stop();
if (!success) failedEvents++;
Util.IsValid(selectedTree);
newTrees.Add(selectedTree);
} else {
stopwatch.Start();
// crossover
SymbolicExpressionTree par0 = null;
SymbolicExpressionTree par1 = null;
do {
par0 = (SymbolicExpressionTree)trees.SampleRandom(random).Clone();
par1 = (SymbolicExpressionTree)trees.SampleRandom(random).Clone();
} while (par0.Length > MAX_TREE_LENGTH || par1.Length > MAX_TREE_LENGTH);
var newTree = SubtreeCrossover.Cross(random, par0, par1, 0.9, MAX_TREE_LENGTH, MAX_TREE_DEPTH);
stopwatch.Stop();
Util.IsValid(newTree);
newTrees.Add(newTree);
}
}
trees = new List<ISymbolicExpressionTree>(newTrees);
newTrees.Clear();
}
var msPerOperation = stopwatch.ElapsedMilliseconds / ((double)POPULATION_SIZE * (double)N_ITERATIONS);
Console.WriteLine("AllArchitectureAlteringOperators: " + Environment.NewLine +
"Operations / s: ~" + Math.Round(1000.0 / (msPerOperation)) + "operations / s)" + Environment.NewLine +
"Failed events: " + failedEvents * 100.0 / (double)(POPULATION_SIZE * N_ITERATIONS / 2.0) + "%" + Environment.NewLine +
Util.GetSizeDistributionString(trees, 200, 5) + Environment.NewLine +
Util.GetFunctionDistributionString(trees) + Environment.NewLine +
Util.GetNumberOfSubtreesDistributionString(trees) + Environment.NewLine +
Util.GetTerminalDistributionString(trees) + Environment.NewLine
);
Assert.IsTrue(failedEvents * 100.0 / (POPULATION_SIZE * N_ITERATIONS / 2.0) < 75.0); // 25% of architecture operations must succeed
//mkommend: commented due to performance issues on the builder
// Assert.IsTrue(Math.Round(1000.0 / (msPerOperation)) > 800); // must achieve more than 800 ops per second
}
示例10: GenerateValues
protected override List<List<double>> GenerateValues() {
List<List<double>> data = new List<List<double>>();
for (int i = 0; i < AllowedInputVariables.Count(); i++) {
data.Add(Enumerable.Range(0, TestPartitionEnd)
.Select(_ => xRandom.NextDouble())
.ToList());
}
var random = new MersenneTwister();
var selectedFeatures =
Enumerable.Range(0, AllowedInputVariables.Count())
.Where(_ => random.NextDouble() < selectionProbability)
.ToArray();
w = selectedFeatures.Select(_ => weightRandom.NextDouble()).ToArray();
var target = new List<double>();
for (int i = 0; i < data[0].Count; i++) {
var s = selectedFeatures
.Select(index => data[index][i])
.ToArray();
target.Add(ScalarProd(s, w));
}
var targetSigma = target.StandardDeviation();
var noisePrng = new NormalDistributedRandom(random, 0, targetSigma * Math.Sqrt(noiseRatio / (1.0 - noiseRatio)));
data.Add(target.Select(t => t + noisePrng.NextDouble()).ToList());
// set property listing the selected features as string[]
this.selectedFeatures = selectedFeatures.Select(i => AllowedInputVariables[i]).ToArray();
optimalRSquared = 1 - noiseRatio;
return data;
}
示例11: UpdateRealizations
private void UpdateRealizations() {
var realizations = new ItemList<BoolArray>(RealizationsSize);
var rand = new MersenneTwister();
for (var i = 0; i < RealizationsSize; i++) {
var newRealization = new BoolArray(Probabilities.Length);
var countOnes = 0;
do {
countOnes = 0;
for (var j = 0; j < Probabilities.Length; j++) {
newRealization[j] = Probabilities[j] < rand.NextDouble();
if (newRealization[j]) countOnes++;
}
// only generate realizations with at least 4 cities visited
} while (countOnes < 4 && Probabilities.Length > 3);
realizations.Add(newRealization);
}
Realizations = realizations;
}
示例12: Sample
void Sample()
{
Debug.Log("GENERATING RANDOM NUMBERS WITH SEED: " + seed);
mrand = new MersenneTwister(seed);
randomList = new ArrayList();
for (int i = 0; i < samplig_size; i++) {
double myval, rn;
switch (op)
{
case MersenneWindowOptionsType.INT:
rn = mrand.Next();
break;
case MersenneWindowOptionsType.FLOAT:
rn = mrand.NextSingle(true);
break;
case MersenneWindowOptionsType.DOUBLE:
rn = mrand.NextDouble(true);
break;
default:
rn = mrand.Next();
break;
}
if (normalizeToggle) {
myval = UnityNormalDistribution.toNormalDistribution(rn, temperature);
} else {
myval = rn;
}
randomList.Add(myval);
}
randomList.Sort();
this.Repaint();
}
示例13: Test
public static void Test()
{
int i;
MersenneTwister mt = new MersenneTwister();
Console.WriteLine("1000 outputs of genrand_int32()");
for (i = 0; i < 1000; i++)
{
Console.Write("{0} ", mt.NextUnsigned());
if (i % 5 == 4) Console.WriteLine();
}
Console.ReadLine();
Console.WriteLine("1000 outputs of genrand_real2");
for (i = 0; i < 1000; i++)
{
Console.Write("{0} ", mt.NextDouble());
if (i % 5 == 4) Console.WriteLine();
}
}