导入
单例分布
在本节课中,我们将探讨单例分布和伯努利分布。
在上一课中,我们实现了第一个离散分布——“在 min 和 max 之间选择一个整数”的分布。在本章中,我们将探索一些更简单的离散分布。
平凡分布简介
所有离散分布中最简单的一种是平凡分布。让我们来看看它的代码:
1public sealed class Singleton<T> : IDiscreteDistribution<T> 2{ 3 private readonly T t; 4 public static Singleton<T> Distribution(T t) => new Singleton<T>(t); 5 private Singleton(T t) => this.t = t; 6 public T Sample() => t; 7 public IEnumerable<T> Support() 8 { 9 yield return t; 10 } 11 12 public int Weight(T t) => EqualityComparer<T>.Default.Equals(this.t, t) ? 1 : 0; 13 public override string ToString() => $"Singleton[{t}]"; 14}
这是一种概率分布,它百分之百地返回同一个值。你有时也会看到这种分布被称为“狄拉克δ函数”或“克罗内克δ函数”,但我们这里统一称其为单例分布,不再赘述。
这是我们第一次见到输出类型不一定是数值的分布。你可能会想,如果我们将要设计的分布仅限于数值型或平凡型,那我们的分布类型是否根本没必要是泛型?在接下来的课程中,我们会看到如何自然地在概率分布中使用更复杂的类型。
伯努利分布
再来看一种整数值的分布:伯努利分布。它考虑的问题是:“如果我们掷一枚可能不公平的硬币,正面记为 1,反面记为 0,结果会怎样?”该分布的参数通常是硬币出现正面的概率,取值范围在 0.0 到 1.0 之间。
1public sealed class Bernoulli : IDiscreteDistribution<int> 2{ 3 public static IDiscreteDistribution<int> Distribution(int zero, int one) 4 { 5 if (zero < 0 || one < 0 || zero == 0 && one == 0) 6 throw new ArgumentException(); 7 if (zero == 0) return Singleton<int>.Distribution(1); 8 if (one == 0) return Singleton<int>.Distribution(0); 9 return new Bernoulli(zero, one); 10 } 11 12 public int Zero { get; } 13 public int One { get; } 14 private Bernoulli(int zero, int one) 15 { 16 this.Zero = zero; 17 this.One = one; 18 } 19 20 public int Sample() => 21 (SCU.Distribution.Sample() <= 22 ((double)Zero) / (Zero + One)) ? 0 : 1; 23 24 public IEnumerable<int> Support() => Enumerable.Range(0, 2); 25 public int Weight(int x) => x == 0 ? Zero : x == 1 ? One : 0; 26 public override string ToString() => $"Bernoulli[{this.Zero}, {this.One}]"; 27}
确实如此,如果我们画出它的直方图:
1Bernoulli.Distribution(1, 3).Histogram()
得到的结果正如预期:正面的数量是反面的三倍:
10|************* 21|****************************************
实现
以下代码片段总结了本课内容:
1using System; 2 3namespace Probability 4{ 5 class Program 6 { 7 static void Main() 8 { 9 Console.WriteLine("Probability"); 10 Episode05.DoIt(); 11 } 12 } 13}
在下一课中,我们将停止创建经典概率分布的新实现,转而研究如何扩展已有分布。