mirror of
https://github.com/space-wizards/RobustToolbox.git
synced 2026-02-15 03:30:53 +01:00
47 lines
1.6 KiB
C#
47 lines
1.6 KiB
C#
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;
|
||
}
|
||
}
|
||
}
|