void DoShoot(Weapon _weapon, GameObject _projectile) { var _deltaPos = Vector2.zero; if (!Mathf.Approximately(positionDeviation.x, 0)) { _deltaPos.x = (float)SimpleRNG.GetNormal(0, positionDeviation.x); } if (!Mathf.Approximately(positionDeviation.y, 0)) { _deltaPos.y = (float)SimpleRNG.GetNormal(0, positionDeviation.y); } _projectile.transform.Translate(_deltaPos); if (!Mathf.Approximately(directionDeviation, 0)) { var _delta = (float)SimpleRNG.GetNormal(0, directionDeviation); var _rotation = Quaternion.AngleAxis(_delta, Vector3.forward); var _velocity = _projectile.rigidbody2D.velocity; _velocity = _rotation * _velocity; _projectile.rigidbody2D.velocity = _velocity; } }
public SamplingWithReplacement(CompositionCategory cat, PatchNames instrument) { this.MaxIterations = 200; this.MaxLength = 100; this.instrument = instrument; this.category = cat; random = new SimpleRNG(); random.SetSeedFromSystemTime(); model = new MarkovChain<Note>(1); foreach(var comp in cat.Compositions) { foreach(var track in comp.Tracks) { if (!IsValidTrack(track)) continue; var mel = (track.GetMainSequence() as MelodySequence).Clone() as MelodySequence; mel.StandardizeDuration(); model.Add(mel.ToArray()); break;//only first track } } CalculateStats(); }
public void Mutate() { for (int i = 0; i < _jobsLength; i++) { if (SimpleRNG.GetUniform() < _mutationRate) { int r = SimpleRNG.Next(0, _jobsLength); int temp = JobGenes[i]; JobGenes[i] = JobGenes[r]; JobGenes[r] = temp; // Mutate the delay time r = SimpleRNG.Next(0, _modesLength); double mutatedDelay = 0; //mutatedDelay = SimpleRNG.GetExponential(_delayMean); mutatedDelay = SimpleRNG.GetNormal(TimeGenes[r], 1.0); //mutatedDelay = _rand.NextDouble() * _delayMean; if (mutatedDelay < 0.0) { mutatedDelay = 0.0; } TimeGenes[r] = mutatedDelay; } } //Mutate the Mode vector: for (int i = 0; i < _modesLength; i++) { if (SimpleRNG.GetUniform() < _mutationRate) { ModeGenes[i] = SimpleRNG.Next(0, _numberOfModes); } } }
void BuildNoiseTextures() { PixelsBuffer Content = new PixelsBuffer(NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * 4); PixelsBuffer Content4D = new PixelsBuffer(NOISE_SIZE * NOISE_SIZE * NOISE_SIZE * 16); SimpleRNG.SetSeed(521288629, 362436069); float4 V = float4.Zero; using (BinaryWriter W = Content.OpenStreamWrite()) { using (BinaryWriter W2 = Content4D.OpenStreamWrite()) { for (int Z = 0; Z < NOISE_SIZE; Z++) { for (int Y = 0; Y < NOISE_SIZE; Y++) { for (int X = 0; X < NOISE_SIZE; X++) { V.Set((float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform()); W.Write(V.x); W2.Write(V.x); W2.Write(V.y); W2.Write(V.z); W2.Write(V.w); } } } } } m_Tex_Noise = new Texture3D(m_Device, NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, 1, ImageUtility.PIXEL_FORMAT.R8, ImageUtility.COMPONENT_FORMAT.UNORM, false, false, new PixelsBuffer[] { Content }); m_Tex_Noise4D = new Texture3D(m_Device, NOISE_SIZE, NOISE_SIZE, NOISE_SIZE, 1, ImageUtility.PIXEL_FORMAT.RGBA8, ImageUtility.COMPONENT_FORMAT.UNORM, false, false, new PixelsBuffer[] { Content4D }); }
/// <summary> /// Returns a value in [0,_maxValue[ /// </summary> /// <param name="_maxValue"></param> /// <returns></returns> uint GetUniformInt(uint _maxValue) { ulong value = (ulong)_maxValue * (ulong)SimpleRNG.GetUint(); value >>= 32; return((uint)value); }
public void Crossover(ref ScheduleGenome p2, ref ScheduleGenome o1) { int cutpoint = SimpleRNG.Next(0, _jobsLength); //Debug.Write(Environment.NewLine + "Distance between " + p1 + " - " + p2 + ": " + population[p1].Distance(population[p2])); for (int i = 0; i < _jobsLength; i++) { o1.JobGenes[i] = JobGenes[i]; } Debug.Assert(o1.IsValid(), "Invalid creature before crossover"); List <int> remainder = new List <int>(p2.JobGenes); for (int i = 0; i < cutpoint; i++) { remainder.Remove(JobGenes[i]); } for (int i = cutpoint; i < _jobsLength; i++) { o1.JobGenes[i] = remainder[i - cutpoint]; } Debug.Assert(o1.IsValid(), "Invalid creature after crossover"); RealCrossover(ref p2, ref o1); CombinationCrossover(ref p2, ref o1); }
public void RandomInit() { List <int> randarray = new List <int>(); for (int i = 0; i < _jobsLength; i++) { randarray.Add(i); } for (int i = 0; i < _jobsLength; i++) { int r = SimpleRNG.Next(0, _jobsLength - i); JobGenes[i] = randarray[r]; randarray.RemoveAt(r); } for (int i = 0; i < _timesLength; i++) { if (SimpleRNG.GetUniform() < _delayRate) { TimeGenes[i] = SimpleRNG.GetExponential(_delayMean); } else { TimeGenes[i] = 0.0; } ModeGenes[i] = SimpleRNG.Next(0, _numberOfModes); } fitness = -1; }
public void RealCrossover(ref ScheduleGenome p2, ref ScheduleGenome o1) { switch (realCrossover) { case RealCrossoverOp.MeanWithNoise: // Mean-with-noise Crossover: for (int i = 0; i < _modesLength; i++) { double mean = TimeGenes[i] + p2.TimeGenes[i]; mean = mean / 2.0; o1.TimeGenes[i] = SimpleRNG.GetNormal(mean, 0.5); if (o1.TimeGenes[i] < 0.0) { o1.TimeGenes[i] = 0.0; } } break; case RealCrossoverOp.Uniform: // Uniform Crossover: int cutpoint = SimpleRNG.Next(0, _modesLength + 1); for (int i = 0; i < cutpoint; i++) { o1.TimeGenes[i] = TimeGenes[i]; } for (int i = cutpoint; i < _modesLength; i++) { o1.TimeGenes[i] = p2.TimeGenes[i]; } break; } }
//levy flight - refer to url: https://www.mathworks.com/matlabcentral/fileexchange/45112-flower-pollination-algorithm/content/fpa_demo.m public double[] LevyFlight(int subsetSize) { //levy exponent and coefficient. For more details see Chapter 11 of the following book: // Xin-She Yang, Nature-Inspired Optimization Algorithms, Elsevier, (2014). double beta = 3 / 2; double A = Gamma(1 + beta); double B = Math.Sin(Math.PI * beta / 2); double C = Gamma((1 + beta) / 2); double D = (beta - 1) / 2; double E = beta * Math.Pow(2, D); double F = 1 / beta; double sigma = Math.Pow((A * B / (C * E)), F); double G, H, I, step; double[] levyF = new double[subsetSize]; for (int i = 0; i < subsetSize; i++) { double randNum = SimpleRNG.GetNormal();//generate random number with normal distribution G = sigma * randNum; H = SimpleRNG.GetNormal(); I = Math.Abs(H); step = G / Math.Pow(I, F); levyF[i] = 0.01 * step; } return(levyF); }
private double GetTheta() { double x = SimpleRNG.GetUniform(); int index = Math.Min(m_UniformRandom2Angle.Length - 1, (int)Math.Floor(x * m_UniformRandom2Angle.Length)); double value = m_UniformRandom2Angle[index]; return(value); }
public static void RandomizeResult(ref Game game) { //SimpleRNG.SetSeedFromSystemTime(); var blackFavor = (game.BlackPlayer.Rating - game.WhitePlayer.Rating) / 40; var simulatedResult = SimpleRNG.GetNormal(32, 7) + blackFavor; game.BlackResult = MakeProperResult(simulatedResult); game.WhiteResult = 64 - game.BlackResult; }
/// <summary> /// Generates blue noise distribution by randomly swapping pixels in the texture to reach lowest possible score and minimize a specific energy function /// </summary> /// <param name="_randomSeed"></param> /// <param name="_minEnergyThreshold"></param> /// <param name="_maxIterations"></param> /// <param name="_standardDeviationImage">Standard deviation for image space. If not sure, use 2.1</param> /// <param name="_standardDeviationValue">Standard deviation for value space. If not sure, use 1.0</param> /// <param name="_progress"></param> public void Generate(uint _randomSeed, float _minEnergyThreshold, int _maxIterations, float _standardDeviationImage, float _standardDeviationValue, ProgressDelegate _progress) { m_kernelFactorImage = -1.0 / (_standardDeviationImage * _standardDeviationImage); m_kernelFactorValue = -1.0 / (_standardDeviationValue * _standardDeviationValue); // Generate initial white noise SimpleRNG.SetSeed(_randomSeed); for (int Y = 0; Y < m_textureSize; Y++) { for (int X = 0; X < m_textureSize; X++) { m_textures[0][X, Y] = (float)SimpleRNG.GetUniform(); } } // Perform iterations float bestScore = ComputeScore(m_textures[0]); int iterationIndex = 0; while (iterationIndex < _maxIterations && bestScore > _minEnergyThreshold) { // Copy source to target array Array.Copy(m_textures[0], m_textures[1], m_textureTotalSize); // Swap up to N pixels randomly for (int swapCount = 0; swapCount < MAX_SWAPPED_ELEMENTS_PER_ITERATION; swapCount++) { uint sourceIndex = GetUniformInt(m_textureTotalSize); uint targetIndex = sourceIndex; while (targetIndex == sourceIndex) { targetIndex = GetUniformInt(m_textureTotalSize); // Make sure target index differs! } float temp = Get(m_textures[1], sourceIndex); Set(m_textures[1], sourceIndex, Get(m_textures[1], targetIndex)); Set(m_textures[1], targetIndex, temp); } // Compute new score float score = ComputeScore(m_textures[1]); if (score < bestScore) { // New best score! Swap textures... bestScore = score; float[,] temp = m_textures[0]; m_textures[0] = m_textures[1]; m_textures[1] = temp; } iterationIndex++; if (_progress != null) { _progress(iterationIndex, bestScore, m_textures[0]); // Notify! } } }
private List <int> ShortenOperator(List <int> mutatedValues, int segmentPosition) { int prolongLength = (int)Math.Ceiling(Math.Abs(SimpleRNG.GetNormal())) + 1; int sign = mutatedValues[segmentPosition] / Math.Abs(mutatedValues[segmentPosition]); // Operator can be applied with length less or equal to difference between // maximum length of segment and longest segment if (sign < 0) { int minimum = mutatedValues.Min(); if (prolongLength > Math.Abs(-39 - minimum)) { prolongLength = Math.Abs(-39 - minimum); } } else { int maximum = mutatedValues.Max(); if (prolongLength > 29 - maximum) { prolongLength = 29 - maximum; } } if (prolongLength == 0) { return(mutatedValues); } // Maximum allowed value for shortening operator is the length of the segment if (prolongLength > Math.Abs(mutatedValues[segmentPosition])) { prolongLength = Math.Abs(mutatedValues[segmentPosition]); } mutatedValues[segmentPosition] = sign * (Math.Abs(mutatedValues[segmentPosition]) - prolongLength); if (mutatedValues[segmentPosition] == 0) { if (segmentPosition == 0 || segmentPosition == mutatedValues.Count - 1) { mutatedValues.RemoveAt(segmentPosition); segmentPosition = -1; } else { mutatedValues[segmentPosition - 1] += mutatedValues[segmentPosition + 1]; mutatedValues.RemoveRange(segmentPosition, 2); segmentPosition = -1; } } int randomParallelSegmentIndex = FindRandomParalellSegment(mutatedValues, segmentPosition, sign > 0); mutatedValues[randomParallelSegmentIndex] = sign * (Math.Abs(mutatedValues[randomParallelSegmentIndex]) + prolongLength); return(mutatedValues); }
private void BuildRandomBuffer() { Reg(m_SB_Random = new StructuredBuffer <float4>(m_Device, RANDOM_TABLE_SIZE, true)); for (int i = 0; i < RANDOM_TABLE_SIZE; i++) { // m_SB_Random.m[i] = new float4( (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform(), (float) SimpleRNG.GetUniform() ); m_SB_Random.m[i] = new float4((float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform(), (float)SimpleRNG.GetUniform(), -(float)Math.Log(1e-3 + (1.0 - 1e-3) * SimpleRNG.GetUniform())); } m_SB_Random.Write(); }
/// <summary> /// Randomly fills bottom states /// </summary> public void Init() { for (int X = 0; X < m_size; X++) { for (int Z = 0; Z < m_size; Z++) { m_grid[X, m_size - 1, Z] = (byte)(1 + (SimpleRNG.GetUint() & 1)); } } }
private void GenerateRays(int _raysCount, StructuredBuffer <float3> _target) { _raysCount = Math.Min(MAX_THREADS, _raysCount); // Half-Life 2 basis float3[] HL2Basis = new float3[] { new float3((float)Math.Sqrt(2.0 / 3.0), 0.0f, (float)Math.Sqrt(1.0 / 3.0)), new float3(-(float)Math.Sqrt(1.0 / 6.0), (float)Math.Sqrt(1.0 / 2.0), (float)Math.Sqrt(1.0 / 3.0)), new float3(-(float)Math.Sqrt(1.0 / 6.0), -(float)Math.Sqrt(1.0 / 2.0), (float)Math.Sqrt(1.0 / 3.0)) }; float centerTheta = (float)Math.Acos(HL2Basis[0].z); float[] centerPhi = new float[] { (float)Math.Atan2(HL2Basis[0].y, HL2Basis[0].x), (float)Math.Atan2(HL2Basis[1].y, HL2Basis[1].x), (float)Math.Atan2(HL2Basis[2].y, HL2Basis[2].x), }; for (int rayIndex = 0; rayIndex < _raysCount; rayIndex++) { double phi = (Math.PI / 3.0) * (2.0 * SimpleRNG.GetUniform() - 1.0); // Stratified version double theta = (Math.Acos(Math.Sqrt((rayIndex + SimpleRNG.GetUniform()) / _raysCount))); // // Don't give a shit version (a.k.a. melonhead version) // // double Theta = Math.Acos( Math.Sqrt(WMath.SimpleRNG.GetUniform() ) ); // double Theta = 0.5 * Math.PI * WMath.SimpleRNG.GetUniform(); theta = Math.Min(0.499f * Math.PI, theta); double cosTheta = Math.Cos(theta); double sinTheta = Math.Sin(theta); double lengthFactor = 1.0 / sinTheta; // The ray is scaled so we ensure we always walk at least a texel in the texture cosTheta *= lengthFactor; sinTheta *= lengthFactor; // Yeah, yields 1... :) _target.m[0 * MAX_THREADS + rayIndex].Set((float)(Math.Cos(centerPhi[0] + phi) * sinTheta), (float)(Math.Sin(centerPhi[0] + phi) * sinTheta), (float)cosTheta); _target.m[1 * MAX_THREADS + rayIndex].Set((float)(Math.Cos(centerPhi[1] + phi) * sinTheta), (float)(Math.Sin(centerPhi[1] + phi) * sinTheta), (float)cosTheta); _target.m[2 * MAX_THREADS + rayIndex].Set((float)(Math.Cos(centerPhi[2] + phi) * sinTheta), (float)(Math.Sin(centerPhi[2] + phi) * sinTheta), (float)cosTheta); } _target.Write(); }
public override Vector3 ReadSensor() { float distanceMod = System.Convert.ToSingle(SimpleRNG.GetNormal(DEFAULT_MEAN, standardDeviation)); float angleMod = Random.Range(MIN_GEN_ANGLE, MAX_GEN_ANGLE); Vector3 modificator = CoordinatesConverter.PolarToCartesian(distanceMod, angleMod); Vector3 result = transform.position + modificator; UpdateMarker(result); recorder.SetData(transform.position.x.ToString(), REC_X_TAG); recorder.SetData(transform.position.z.ToString(), REC_Z_TAG); return(result); }
private void ShowFlag(string guid, double value) { var direction = SimpleRNG.GetUniform() > 0.5 ? FlagDirection.Up : FlagDirection.Down; var flag = new Flag { Id = guid, Value = value, FlagDirection = direction.ToString() }; foreach (var h in _handlers) { h.Value(flag); } }
public void CombinationCrossover(ref ScheduleGenome p2, ref ScheduleGenome o1) { int cutpoint = SimpleRNG.Next(0, _modesLength); for (int i = 0; i < cutpoint; i++) { o1.ModeGenes[i] = p2.ModeGenes[i]; } for (int i = cutpoint; i < _modesLength; i++) { o1.ModeGenes[i] = ModeGenes[i]; } }
/// <summary> /// Set the random turn component of the AI. /// </summary> private float randTurn() { float offset = 2.0f; float radius = 1.0f; float maxRotation = MathHelper.Pi / 7.0f; currentRotation += (float)(SimpleRNG.GetUniform() * 2 - 1) * maxRotation; float width = (float)Math.Sin(currentRotation) * radius; float extra = (float)Math.Cos(currentRotation) * radius; return((float)Math.Tanh(width / (offset + extra))); }
public GA(int seed, int popsize, int offsize, double deathRate) { _seed = seed; SimpleRNG.SetSeed((uint)_seed, (uint)_seed + 1); _popsize = popsize; _offsize = offsize; _deathRate = deathRate; population = new ScheduleGenome[_popsize]; offspring = new ScheduleGenome[_offsize]; // Default operator options: realCrossover = RealCrossoverOp.MeanWithNoise; survivalSelection = SurvivalSelectionOp.Elitist; parentSelection = ParentSelectionOp.Tournament; }
public void UpdateStonesAtPatch(IntVector2 patchCoord, Transform patchHolder) { // reset SimpleRNG using cactus seed SimpleRNG.SetSeed((uint)(stoneSeed + patchCoord.x + patchCoord.y * terrainManager.worldPatchesX)); // set RNG seed depending on stone seed, world seed, and patch coordinates stoneRNG = new System.Random(stoneSeed + patchCoord.x + patchCoord.y * terrainManager.worldPatchesX); // in plain terrain float stonePlainDensityHere = stonePlainDensity.min + (float)stoneRNG.NextDouble() * (stonePlainDensity.max - stonePlainDensity.min); for (int i = 0; i < stonePlainDensityHere; i++) { Vector3 point = loadSceneryAndLore.GetValidRandomPositionInPatch(patchCoord, 1f, stoneRNG); float slope = terrainManager.GetSlopeAtPoint(point.x, point.z); //Debug.Log(point + ", " + slope); if (slope > stonePlainSlope.min && slope < stonePlainSlope.max) { GameObject temp = Instantiate(stonePlainPrefabs[stoneRNG.Next(stonePlainPrefabs.Length)], point, Quaternion.identity); temp.transform.localScale = Vector3.one * (stonePlainScale.min + (float)stoneRNG.NextDouble() * (stonePlainScale.max - stonePlainScale.min)); temp.transform.Translate(stonePlainOffset * temp.transform.localScale.x); temp.transform.Rotate(Vector3.up * (float)stoneRNG.NextDouble() * 360f); temp.transform.parent = patchHolder.transform; } } // in cliffs float stoneCliffDensityHere = stoneCliffDensity.min + (float)stoneRNG.NextDouble() * (stoneCliffDensity.max - stoneCliffDensity.min); for (int i = 0; i < stoneCliffDensityHere; i++) { Vector3 point = loadSceneryAndLore.GetValidRandomPositionInPatch(patchCoord, 1f, stoneRNG); float slope = terrainManager.GetSlopeAtPoint(point.x, point.z); if (slope > stoneCliffSlope.min && slope < stoneCliffScale.max) { GameObject temp = Instantiate(stoneCliffPrefabs[stoneRNG.Next(stoneCliffPrefabs.Length)], point, Quaternion.identity); temp.transform.localScale = Vector3.one * (stoneCliffScale.min + (float)stoneRNG.NextDouble() * (stoneCliffScale.max - stoneCliffScale.min)); // re-scale temp.transform.Translate(stoneCliffOffset * temp.transform.localScale.x); // apply downwards offset temp.transform.Rotate(Vector3.up * (float)stoneRNG.NextDouble() * 360f); temp.transform.parent = patchHolder.transform; } } }
public void TestStandardDeviationForGame() { const int numSamples = 100000; var rs = new RunningStat(); rs.Clear(); var mean = 32; var stdev = 7; for (int i = 0; i < numSamples; ++i) { rs.Push(SimpleRNG.GetNormal(mean, stdev)); } PrintStatisticResults("normal", mean, stdev * stdev, rs.Mean(), rs.Variance(), rs.resultlist.Min(), rs.resultlist.Max()); PrintGameResultStats(rs); }
public void InitializeWeightsAndBiases() { SimpleRNG.SetSeedFromSystemTime(); for (int layer = 0; layer < neuralNetAccessor.NumberOfLayers; layer++) { for (int node = 0; node < neuralNetAccessor.NodesInLayer(layer); node++) { var sigmoid = neuralNetAccessor.GetSigmoid(layer, node); sigmoid.Bias = (float)SimpleRNG.GetNormal(0, 1); float standardDeviation = 1.0f / Mathf.Sqrt(sigmoid.Weights.Length); for (int i = 0; i < sigmoid.Weights.Length; i++) { sigmoid.Weights[i] = (float)SimpleRNG.GetNormal(0, standardDeviation); } } } }
void Reset() { m_StepCount = 0; int CellsCount = (int)Math.Sqrt(PARTICLES_COUNT); for (int i = 0; i < PARTICLES_COUNT; i++) { int CellY = (i / CellsCount) - CellsCount / 2; int CellX = (i % CellsCount) - CellsCount / 2; // Point2D Pos = new Point2D( SIMULATION_SPACE_SIZE * (float) SimpleRNG.GetNormal(), SIMULATION_SPACE_SIZE * (float) SimpleRNG.GetNormal() ); Point2D Pos = new Point2D(40.0f * (CellX + (float)SimpleRNG.GetNormal()), 40.0f * (CellY + (float)SimpleRNG.GetNormal())); m_Particles[0][i].P = m_Particles[1][i].P = Pos; m_Particles[0][i].Size = m_Particles[1][i].Size = 0; } }
private Individual MutateIndividual(Individual individual) { int mutationEffect = random.Next(0, 2); if (mutationEffect == 0) { double value = random.NextDouble(); for (int i = 0; i < individual.References.Count; i++) { double chance = random.NextDouble(); if (chance < value) { int xChange = (int)(SimpleRNG.GetNormal()); int yChange = (int)(SimpleRNG.GetNormal()); int xSign = Math.Sign(SimpleRNG.GetNormal()); int ySign = Math.Sign(SimpleRNG.GetNormal()); individual.References[i].X += xSign * xChange; individual.References[i].Y += ySign * yChange; } } } else { double value = random.NextDouble(); for (int i = 0; i < individual.References.Count; i++) { double chance = random.NextDouble(); if (chance < value) { int randX = random.Next(1, 33); int randY = random.Next(6, 28); individual.References[i].X = randX; individual.References[i].Y = randY; } } } return(individual); }
public void Initialize() { simpleRng = new SimpleRNG(); animationCurveSampler = new AnimationCurveSampler(probabilityCurve); //Clear LowDiscrepancyList lowDiscrepancyValues.Clear(); //Seed switch (seedType) { case SeedType.GenerateSeed: //generate random seed simpleRng.SetSeedFromSystemTime(); break; case SeedType.CustomSeed: //use custom seed simpleRng.SetSeed(customSeed); break; } }
private int SelectParent() { int p = 0; switch (parentSelection) { case ParentSelectionOp.FitnessProportional: double totalFitness = 0; for (int i = 0; i < _popsize; i++) { totalFitness += population[i].fitness; } //double r = _rand.NextDouble() * totalFitness; double r = SimpleRNG.GetUniform() * totalFitness; double runningTotal = population[p].fitness; while (runningTotal > r) { p++; runningTotal += population[p].fitness; } break; case ParentSelectionOp.Tournament: int k = _popsize / 10; //p = _rand.Next(_popsize); p = (int)(SimpleRNG.GetUniform() * _popsize); double bestfitness = population[p].fitness; for (int i = 0; i < k; i++) { int px = SimpleRNG.Next(0, _popsize); if (population[px].fitness > bestfitness) { bestfitness = population[px].fitness; p = px; } } break; } return(p); }
public Action StartSparkline(IEnumerable <AddTimeValue> addTimeValues) { Func <int> tickTime = () => { // Convert.ToInt32(Math.Floor(SimpleRNG.GetUniform()*2000)); return(1000 / 2); }; Func <AddTimeValue, Action> tickGenerator = addTimeValue => { var x = 100.0; return(() => { while (true) { var newx = x + SimpleRNG.GetNormal() * 2; if (newx < 0.0) { newx = 0.0; } _dispatcher.BeginInvoke((Action)(() => { var guid = addTimeValue(newx); if (SimpleRNG.GetUniform() > 0.75) { ShowFlag(guid, newx); } })); x = newx; Thread.Sleep(tickTime()); } }); }; Func <Action, WaitCallback> toWaitCallback = gen => wc => gen(); Action start = () => { var tickGenerators = addTimeValues.Select(tickGenerator).ToArray(); foreach (var generateTicks in tickGenerators) { ThreadPool.QueueUserWorkItem(toWaitCallback(generateTicks)); } }; return(start); }
private void InitialiseGraph() { float[] position = new float[this.input_dim]; float[] position2 = new float[this.input_dim]; SimpleRNG r = new SimpleRNG(); double r1 = SimpleRNG.GetNormal(); double r2 = SimpleRNG.GetNormal(); double r3 = SimpleRNG.GetNormal(); double r4 = SimpleRNG.GetNormal(); position[0] = (float)r1; position[1] = (float)r2; position2[0] = (float)r3; position2[1] = (float)r4; this.graph.AddNode(position, tlen); this.graph.AddNode(position2, tlen); }
public Form1() { InitializeComponent(); for (int x = 0; x <= 100; x++) { float sigma = Math.Max(1e-4f, GRAPH_WIDTH * x / 100); double avgNormal = 0.0f; for (int i = 0; i < 10000; i++) { double rnd = SimpleRNG.GetNormal(0, sigma); rnd = rnd % Math.PI; // Simple wrapping (https://en.wikipedia.org/wiki/Wrapped_distribution) // rnd = rnd % (2.0*Math.PI); // Simple wrapping (https://en.wikipedia.org/wiki/Wrapped_distribution) avgNormal += Math.Cos(rnd); } avgNormal /= 10000; m_distribution.Add(new float2(sigma, (float)avgNormal)); } panelOutput.UpdateBitmap(); }