Search⌘ K
AI Features

Singleton Distribution

Explore how to create and use singleton and Bernoulli distributions in C#, mastering simple discrete probability models. Learn how the singleton returns a fixed value every time and how Bernoulli simulates a biased coin flip with outcomes weighted by probability.

In the previous lesson, we implemented our first discrete distribution, the “choose an integer between min and max” distribution. In this chapter, we will explore easier discrete distributions.


Introduction to Trivial Distribution

The easiest discrete distribution of all is the trivial distribution. Let’s have a look at its code:

public sealed class Singleton<T> : IDiscreteDistribution<T>
{
  private readonly T t;
  public static Singleton<T> Distribution(T t) => new Singleton<T>(t);
  private Singleton(T t) => this.t = t;
  public T Sample() => t;
  public IEnumerable<T> Support()
  {
    yield return t;
  }

  public int Weight(T t) => EqualityComparer<T>.Default.Equals(this.t, t) ? 1 :
...