Files
RobustToolbox/Robust.Shared.Maths/RandomExtensions.cs
2019-04-27 21:16:30 +02:00

47 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections.Generic;
namespace Robust.Shared.Maths
{
public static class RandomExtensions
{
/// <summary>
/// Generate a random number from a normal (gaussian) distribution.
/// </summary>
/// <param name="random">The random object to generate the number from.</param>
/// <param name="μ">The average or "center" of the normal distribution.</param>
/// <param name="σ">The standard deviation of the normal distribution.</param>
public static double NextGaussian(this Random random, double μ = 0, double σ = 1)
{
// https://stackoverflow.com/a/218600
var α = random.NextDouble();
var β = random.NextDouble();
var randStdNormal = Math.Sqrt(-2.0 * Math.Log(α)) * Math.Sin(2.0 * Math.PI * β);
return μ + σ * randStdNormal;
}
public static T Pick<T>(this Random random, IReadOnlyList<T> list)
{
var index = random.Next(list.Count);
return list[index];
}
public static float NextFloat(this Random random)
{
return (float)random.NextDouble();
}
/// <summary>
/// Have a certain chance to return a boolean.
/// </summary>
/// <param name="random">The random instance to run on.</param>
/// <param name="chance">The chance to pass, from 0 to 1.</param>
public static bool Prob(this Random random, float chance)
{
return random.NextDouble() <= chance;
}
}
}