public static void subdivide(Vector2 A, Vector2 B, Vector2 C, Vector2 D, int minLength, System.Random random){

		if ((A - C).magnitude < minLength || (B - D).magnitude < minLength) {
			return;
		}
		
		var p = (float)random.NextDouble (0.2, 0.8);
		var q = (float)random.NextDouble (0.2, 0.8);
		//var p = Random.Range(0.2F, 0.8F);
		//var q = Random.Range (0.2F, 0.8F);
		
		var E = Vector2.Lerp (A, D, p);
		var F = Vector2.Lerp (B, C, p);
		var G = Vector2.Lerp (A, B, q);
		var I = Vector2.Lerp (D, C, q);
		
		var H = Vector2.Lerp (E, F, q);
		
		var s = 1.0F - (float)random.NextDouble (-1.0, +1.0);
		var t = 1.0F - (float)random.NextDouble (-1.0, +1.0);
		//var s = 1.0F - Random.Range (-0.9F, +0.9F);
		//var t = 1.0F - Random.Range (-0.9F, +0.9F);

		subdivide (A, Vector2.Lerp (G, B, s), H, Vector2.Lerp (E, D, t), minLength, random);
		points.Add (H);
		subdivide (H, Vector2.Lerp (F, C, s), H, Vector2.Lerp (I, D, t), minLength, random);
	}
Beispiel #2
0
    //RNG with Gaussian distribution
    public static float NextGaussian(ref System.Random rnd)
    {
        float NextGaussian_v1, NextGaussian_v2, NextGaussian_s;
        do
        {
            NextGaussian_v1 = 2.0f * (float)rnd.NextDouble() - 1.0f;
            NextGaussian_v2 = 2.0f * (float)rnd.NextDouble() - 1.0f;
            NextGaussian_s = NextGaussian_v1 * NextGaussian_v1 + NextGaussian_v2 * NextGaussian_v2;
        } while (NextGaussian_s >= 1.0f || NextGaussian_s == 0f);

        NextGaussian_s = Mathf.Sqrt((-2.0f * Mathf.Log(NextGaussian_s)) / NextGaussian_s);

        return NextGaussian_v1 * NextGaussian_s;
    }
Beispiel #3
0
 // this Neuron is initialited with random weights
 // and Input.input values at 0
 public Neuron(int n_weights, System.Random rand, bool bias = true)
 {
     // Input fill
     Input tmp;
     this.inputs = new List<Input>();
     if(bias)
         inputs.Add(new Input { input = 1, weight = rand.NextDouble()*2-1 });//set bias between -1 & 1
     for (int i = 0; i < n_weights; i++)
     {
         tmp = new Input();
         tmp.weight = rand.NextDouble()*2-1;//weigths between -1 and 1
         tmp.input = 0;
         inputs.Add(tmp);
     }
 }
 public SimplexAlgorithm(System.Random random)
 {
     for(int k=0;k<512;k++)
     {
         perm[k]=p[k & 255];
     }
     // To randomise the noise swap p[] values randomly
     for(int n=0;n<grad3.Length;n++)
     {
         int a = (int)(random.NextDouble()*grad3.Length);
         int b = (int)(random.NextDouble()*grad3.Length);
         int[] tmp = grad3[b];
         grad3[b] = grad3[a];
         grad3[a] = tmp;
     }
 }
Beispiel #5
0
        public ResourceItem(ConfigNode data, string resource, string body, string type, System.Random random)
        {
            DefaultResource defaultResource = DefaultLibrary.GetDefault(MapGenerator.DefaultName).GetBody(body).GetResourceOfType(resource, type);
            this.resource = PartResourceLibrary.Instance.GetDefinition(data.GetValue("name"));
            this.type = KRESUtils.GetResourceType(type);
            this.map = null;
            if (!data.TryGetValue("actualDensity", ref actualDensity))
            {
                actualDensity = KRESUtils.Clamp01(defaultResource.Density * (0.97d + (random.NextDouble() * 0.06d)));
            }

            if (!data.TryGetValue("actualError", ref actualError))
            {
                actualError = (random.NextDouble() * 2d) - 1d;
                data.AddValue("actualError", actualError);
            }
        }
Beispiel #6
0
        public UpdateOutcome Update(System.Random random)
        {
            if (random.NextDouble() > 0.5)
            {
                Health = Math.Max(0f, Math.Min(Health + (float)(random.NextDouble() - 0.5) / 10f, 1f)); // chance of varying up to 10% of our health

                // Dead?
                if (Health <= 0f)
                    return UpdateOutcome.Removed;
 
                X += (float)(random.NextDouble() - 0.5) * 2f;
                Z += (float)(random.NextDouble() - 0.5) * 2f;
                return UpdateOutcome.Changed;
            }

            return UpdateOutcome.None;
        }
Beispiel #7
0
 private void _generateNoise(System.Random rng, TerrainData data)
 {
     int width = data.Width;
     int height = data.Height;
     for (int y = 0; y < height; y++)
     {
         for(int x = 0; x < width; x++)
         {
             data.SetValue(x, y, rng.NextDouble() < m_randomFillChance ? 1 : 0);
         }
     }
 }
Beispiel #8
0
 public bool read_weight(System.Random rnd)
 {
     if (System.IO.File.Exists(@"weights\" + layer + "_" + number + "_" + pos + ".txt"))
     {
         using (var str = new System.IO.StreamReader(@"weights\" + layer + "_" + number + "_" + pos + ".txt")){
         string line;
         for (int i = 0; i < size; i++)
             if((line=str.ReadLine())!=null)
                 weight[i] = System.Single.Parse(line);
             else
                 weight[i] = (float)((rnd.NextDouble() / 1.65 - 0.3)) / 10;
         }
     }
     else
     {
         for (int i = 0; i < size; i++)
             weight[i] = (float)((rnd.NextDouble() / 1.65 - 0.3))/10;
         weight[size] = (float)((1 + 0.5 / 10000 - (rnd.NextDouble() / 10000))); //Initialize BIAS
         return false;
     }
     return true;
 }
Beispiel #9
0
 public Neuron(List<double> weight, System.Random rand, bool bias = true)
 {
     // Input fill
     Input tmp;
     this.inputs = new List<Input>();
     if(bias)
         inputs.Add(new Input { input = 1, weight = rand.NextDouble() * 2 - 1 });//set bias between -1 & 1
     for (int i = 0; i < weight.Count; i++)
     {
         tmp = new Input();
         tmp.weight = weight[i]; tmp.input = 0;
         inputs.Add(tmp);
     }
 }
 public int OnRadiation(double energy, int count, System.Random random)
 {
     #if QUITEDEBUG
     Logging.Log(String.Format("{0} struck by {1:D} rays of energy {2:G}", part.partInfo.title, count, energy), false);
     #endif
     if (random.NextDouble() < Math.Exp(-50.0/energy))
     {
         if (initChargeRate < chargeRate)
             initChargeRate = chargeRate;
         chargeRate *= (float)Math.Pow(1.0 - 1.0 / (initChargeRate * 2e5f), count);
         #if DEBUG
         Logging.Log(String.Format("{0} degraded chargeRate to {1:G}", part.partInfo.title, chargeRate), false);
         #endif
         return 0;
     }
     return count;
 }
Beispiel #11
0
 //public Neuron(List<double> weight , List<double> input, double biais)
 public Neuron(List<double> weight, List<double> input, System.Random rand, bool bias = true)
 {
     if(weight.Count != input.Count)
     {
         Debug.Log("The weight and the input list have different size ! What did you expect ?");
         throw new IndexOutOfRangeException();
     }
     // Input fill
     Input tmp;
     this.inputs = new List<Input>();
     if(bias)
         inputs.Add(new Input { input = 1, weight = rand.NextDouble() * 2 - 1 });//set bias between -1 & 1
     for (int i = 0; i < weight.Count; i++)
     {
         tmp = new Input();
         tmp.weight = weight[i]; tmp.input = input[i];
         inputs.Add(tmp);
     }
     // Take the descision
     main(inputs);
 }
Beispiel #12
0
        public ResourceItem(ConfigNode data, string resource, string body, System.Random random)
        {
            DefaultResource defaultResource = DefaultLibrary.GetDefault(MapGenerator.DefaultName).GetBody(body).GetResourceOfType(resource, "ore");
            this.resource = PartResourceLibrary.Instance.GetDefinition(resource);
            this.type = ResourceType.ORE;
            double density = defaultResource.Density;
            this.map = new ResourceMap(defaultResource, body);
            if (!data.TryGetValue("actualDensity", ref actualDensity))
            {
                Texture2D texture = Map.GetTexture();
                actualDensity = texture.GetPixels().Count(p => p.a > 0) / mapResolution;
                Texture2D.Destroy(texture);
                data.AddValue("actualDensity", actualDensity);
            }

            if (!data.TryGetValue("actualError", ref actualError))
            {
                actualError = (random.NextDouble() * 2d) - 1d;
                data.AddValue("actualError", actualError);
            }
        }
Beispiel #13
0
        /// <summary>
        /// This function 'ticks' the particle, i.e moves it on a stage.
        /// </summary>
        /// <param name="rand">A random object.</param>
        public override void Tick(System.Random rand)
        {
            //	Randomise the direction.
            direction.X = directionRandomise.X - (2 * (float)rand.NextDouble() * directionRandomise.X);
            direction.Y = directionRandomise.Y - (2 * (float)rand.NextDouble() * directionRandomise.Y);
            direction.Z = directionRandomise.Z - (2 * (float)rand.NextDouble() * directionRandomise.Z);

            //	Now we randomise the color.
            color.R += colorRandomise.R - (2 * (float)rand.NextDouble() * colorRandomise.R);
            color.G += colorRandomise.G - (2 * (float)rand.NextDouble() * colorRandomise.G);
            color.B += colorRandomise.B - (2 * (float)rand.NextDouble() * colorRandomise.B);
            color.A += colorRandomise.A - (2 * (float)rand.NextDouble() * colorRandomise.A);

            //	First we update the velocity.
            velocity += direction;
            velocity += gravity;

            //	Now we move the particle.
            position += velocity;
            life -= lifespan;
        }
Beispiel #14
0
 /// <summary>
 /// Samples a negative binomial distributed random variable.
 /// </summary>
 /// <param name="rnd">The random number generator to use.</param>
 /// <param name="r">The number of failures (r) until the experiment stopped. Range: r ≥ 0.</param>
 /// <param name="p">The probability (p) of a trial resulting in success. Range: 0 ≤ p ≤ 1.</param>
 /// <returns>a sample from the distribution.</returns>
 static int SampleUnchecked(System.Random rnd, double r, double p)
 {
     var lambda = Gamma.SampleUnchecked(rnd, r, p);
     var c = Math.Exp(-lambda);
     var p1 = 1.0;
     var k = 0;
     do
     {
         k = k + 1;
         p1 = p1*rnd.NextDouble();
     } while (p1 >= c);
     return k - 1;
 }
        /// <summary>
        /// <para>Sampling implementation based on:
        /// "A Simple Method for Generating Gamma Variables" - Marsaglia &amp; Tsang
        /// ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000, Pages 363–372.</para>
        /// <para>This method performs no parameter checks.</para>
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="shape">The shape of the Gamma distribution.</param>
        /// <param name="invScale">The inverse scale of the Gamma distribution.</param>
        /// <returns>A sample from a Gamma distributed random variable.</returns>
        internal static double SampleGamma(System.Random rnd, double shape, double invScale)
        {
            if (Double.IsPositiveInfinity(invScale))
            {
                return shape;
            }
            else
            {
                double a = shape;
                double alphafix = 1.0;

                // Fix when alpha is less than one.
                if (shape < 1.0)
                {
                    a = shape + 1.0;
                    alphafix = System.Math.Pow(rnd.NextDouble(), 1.0 / shape);
                }

                double d = a - (1.0 / 3.0);
                double c = 1.0 / System.Math.Sqrt(9.0 * d);
                while (true)
                {
                    double x = Normal.Sample(rnd, 0.0, 1.0);
                    double v = 1.0 + (c * x);
                    while (v <= 0.0)
                    {
                        x = Normal.Sample(rnd, 0.0, 1.0);
                        v = 1.0 + (c * x);
                    }

                    v = v * v * v;
                    double u = rnd.NextDouble();
                    x = x * x;
                    if (u < 1.0 - (0.0331 * x * x))
                    {
                        return alphafix * d * v / invScale;
                    }

                    if (System.Math.Log(u) < (0.5 * x) + (d * (1.0 - v + System.Math.Log(v))))
                    {
                        return alphafix * d * v / invScale;
                    }
                }
            }
        }
Beispiel #16
0
 /// <summary>
 /// Returns one sample from the distribution.
 /// </summary>
 /// <param name="rnd">The random number generator to use.</param>
 /// <param name="p">The probability (p) of generating one. Range: 0 ≤ p ≤ 1.</param>
 /// <returns>One sample from the distribution implied by <paramref name="p"/>.</returns>
 static int SampleUnchecked(System.Random rnd, double p)
 {
     return p == 1.0 ? 1 : (int)Math.Ceiling(Math.Log(1.0 - rnd.NextDouble(), 1.0 - p));
 }
Beispiel #17
0
 static double SampleUnchecked(System.Random rnd, double location, double scale)
 {
     return location + scale*Math.Tan(Constants.Pi*(rnd.NextDouble() - 0.5));
 }
Beispiel #18
0
 static IEnumerable<double> SamplesUnchecked(System.Random rnd, double location, double scale)
 {
     while (true)
     {
         yield return location + scale*Math.Tan(Constants.Pi*(rnd.NextDouble() - 0.5));
     }
 }
Beispiel #19
0
        /// <summary>
        /// <para>Sampling implementation based on:
        /// "A Simple Method for Generating Gamma Variables" - Marsaglia &amp; Tsang
        /// ACM Transactions on Mathematical Software, Vol. 26, No. 3, September 2000, Pages 363–372.</para>
        /// <para>This method performs no parameter checks.</para>
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="shape">The shape (k, α) of the Gamma distribution. Range: α ≥ 0.</param>
        /// <param name="rate">The rate or inverse scale (β) of the Gamma distribution. Range: β ≥ 0.</param>
        /// <returns>A sample from a Gamma distributed random variable.</returns>
        internal static double SampleUnchecked(System.Random rnd, double shape, double rate)
        {
            if (double.IsPositiveInfinity(rate))
            {
                return shape;
            }

            var a = shape;
            var alphafix = 1.0;

            // Fix when alpha is less than one.
            if (shape < 1.0)
            {
                a = shape + 1.0;
                alphafix = Math.Pow(rnd.NextDouble(), 1.0/shape);
            }

            var d = a - (1.0/3.0);
            var c = 1.0/Math.Sqrt(9.0*d);
            while (true)
            {
                var x = Normal.Sample(rnd, 0.0, 1.0);
                var v = 1.0 + (c*x);
                while (v <= 0.0)
                {
                    x = Normal.Sample(rnd, 0.0, 1.0);
                    v = 1.0 + (c*x);
                }

                v = v*v*v;
                var u = rnd.NextDouble();
                x = x*x;
                if (u < 1.0 - (0.0331*x*x))
                {
                    return alphafix*d*v/rate;
                }

                if (Math.Log(u) < (0.5*x) + (d*(1.0 - v + Math.Log(v))))
                {
                    return alphafix*d*v/rate;
                }
            }
        }
Beispiel #20
0
 static double SampleUnchecked(System.Random rnd, double scale)
 {
     return scale*Math.Sqrt(-2.0*Math.Log(rnd.NextDouble()));
 }
 /// <summary>
 /// Returns a random range float, adapted for threading.
 /// </summary>
 /// <returns>The range.</returns>
 /// <param name="random">Random.</param>
 /// <param name="min">Minimum.</param>
 /// <param name="max">Max.</param>
 public static float RandomRange(System.Random random, float min, float max)
 {
     return min+((float)random.NextDouble())*(max-min);
 }
Beispiel #22
0
        /// <summary>
        /// Generates one sample from the Poisson distribution by Knuth's method.
        /// </summary>
        /// <param name="rnd">The random source to use.</param>
        /// <param name="lambda">The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.</param>
        /// <returns>A random sample from the Poisson distribution.</returns>
        static int DoSampleShort(System.Random rnd, double lambda)
        {
            var limit = Math.Exp(-lambda);
            var count = 0;
            for (var product = rnd.NextDouble(); product >= limit; product *= rnd.NextDouble())
            {
                count++;
            }

            return count;
        }
        /// <summary>
        /// Returns one trials from the categorical distribution.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="cdfUnnormalized">The (unnormalized) cumulative distribution of the probability distribution.</param>
        /// <returns>One sample from the categorical distribution implied by <paramref name="cdfUnnormalized"/>.</returns>
        internal static int SampleUnchecked(System.Random rnd, double[] cdfUnnormalized)
        {
            // TODO : use binary search to speed up this procedure.
            var u = rnd.NextDouble()*cdfUnnormalized[cdfUnnormalized.Length - 1];

            var idx = 0;
            while (u > cdfUnnormalized[idx])
            {
                idx++;
            }

            return idx;
        }
Beispiel #24
0
        /// <summary>
        /// Generates a sequence of samples from the distribution.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="scale">The scale (σ) of the distribution. Range: σ > 0.</param>
        /// <returns>a sequence of samples from the distribution.</returns>
        public static IEnumerable<double> Samples(System.Random rnd, double scale)
        {
            if (scale <= 0.0) throw new ArgumentOutOfRangeException("scale", Resources.InvalidDistributionParameters);

            while (true)
            {
                yield return scale*Math.Sqrt(-2.0*Math.Log(rnd.NextDouble()));
            }
        }
Beispiel #25
0
        /// <summary>
        /// Generates one sample from the Bernoulli distribution.
        /// </summary>
        /// <param name="rnd">The random source to use.</param>
        /// <param name="p">The probability (p) of generating one. Range: 0 ≤ p ≤ 1.</param>
        /// <returns>A random sample from the Bernoulli distribution.</returns>
        static int SampleUnchecked(System.Random rnd, double p)
        {
            if (rnd.NextDouble() < p)
            {
                return 1;
            }

            return 0;
        }
Beispiel #26
0
        internal static void SamplesUnchecked(System.Random rnd, double[] values, double mean, double stddev)
        {
            if (values.Length == 0)
            {
                return;
            }

            // Since we only accept points within the unit circle
            // we need to generate roughly 4/pi=1.27 times the numbers needed.
            int n = (int)Math.Ceiling(values.Length*4*Constants.InvPi);
            if (n.IsOdd())
            {
                n++;
            }

            var uniform = rnd.NextDoubles(n);

            // Polar transform
            double x, y;
            int index = 0;
            for (int i = 0; i < uniform.Length && index < values.Length; i += 2)
            {
                if (!PolarTransform(uniform[i], uniform[i + 1], out x, out y))
                {
                    continue;
                }

                values[index++] = mean + stddev*x;
                if (index == values.Length)
                {
                    return;
                }

                values[index++] = mean + stddev*y;
                if (index == values.Length)
                {
                    return;
                }
            }

            // remaining, if any
            while (index < values.Length)
            {
                if (!PolarTransform(rnd.NextDouble(), rnd.NextDouble(), out x, out y))
                {
                    continue;
                }

                values[index++] = mean + stddev*x;
                if (index == values.Length)
                {
                    return;
                }

                values[index++] = mean + stddev*y;
                if (index == values.Length)
                {
                    return;
                }
            }
        }
Beispiel #27
0
        /// <summary>
        /// Generates one sample from the Poisson distribution by "Rejection method PA".
        /// </summary>
        /// <param name="rnd">The random source to use.</param>
        /// <param name="lambda">The lambda (λ) parameter of the Poisson distribution. Range: λ > 0.</param>
        /// <returns>A random sample from the Poisson distribution.</returns>
        /// <remarks>"Rejection method PA" from "The Computer Generation of Poisson Random Variables" by A. C. Atkinson,
        /// Journal of the Royal Statistical Society Series C (Applied Statistics) Vol. 28, No. 1. (1979)
        /// The article is on pages 29-35. The algorithm given here is on page 32. </remarks>
        static int DoSampleLarge(System.Random rnd, double lambda)
        {
            var c = 0.767 - (3.36/lambda);
            var beta = Math.PI/Math.Sqrt(3.0*lambda);
            var alpha = beta*lambda;
            var k = Math.Log(c) - lambda - Math.Log(beta);

            for (;;)
            {
                var u = rnd.NextDouble();
                var x = (alpha - Math.Log((1.0 - u)/u))/beta;
                var n = (int)Math.Floor(x + 0.5);
                if (n < 0)
                {
                    continue;
                }

                var v = rnd.NextDouble();
                var y = alpha - (beta*x);
                var temp = 1.0 + Math.Exp(y);
                var lhs = y + Math.Log(v/(temp*temp));
                var rhs = k + (n*Math.Log(lambda)) - SpecialFunctions.FactorialLn(n);
                if (lhs <= rhs)
                {
                    return n;
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Generates a sample from the Binomial distribution without doing parameter checking.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="p">The success probability (p) in each trial. Range: 0 ≤ p ≤ 1.</param>
        /// <param name="n">The number of trials (n). Range: n ≥ 0.</param>
        /// <returns>The number of successful trials.</returns>
        static int SampleUnchecked(System.Random rnd, double p, int n)
        {
            var k = 0;
            for (var i = 0; i < n; i++)
            {
                k += rnd.NextDouble() < p ? 1 : 0;
            }

            return k;
        }
 static IEnumerable<double> NextDoubleSequenceEnumerable(System.Random rnd)
 {
     while (true)
     {
         yield return rnd.NextDouble();
     }
 }
        /// <summary>
        /// Returns one trials from the distribution.
        /// </summary>
        /// <param name="rnd">The random number generator to use.</param>
        /// <param name="lambda">The lambda (λ) parameter. Range: λ > 0.</param>
        /// <param name="nu">The rate of decay (ν) parameter. Range: ν ≥ 0.</param>
        /// <param name="z">The z parameter.</param>
        /// <returns>
        /// One sample from the distribution implied by <paramref name="lambda"/>, <paramref name="nu"/>, and <paramref name="z"/>.
        /// </returns>
        static int SampleUnchecked(System.Random rnd, double lambda, double nu, double z)
        {
            var u = rnd.NextDouble();
            var p = 1.0/z;
            var cdf = p;
            var i = 0;

            while (u > cdf)
            {
                i++;
                p = p*lambda/Math.Pow(i, nu);
                cdf += p;
            }

            return i;
        }