How to resolve the algorithm Verify distribution uniformity/Naive step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Verify distribution uniformity/Naive step by step in the Nim programming language

Table of Contents

Problem Statement

This task is an adjunct to Seven-sided dice from five-sided dice.

Create a function to check that the random integers returned from a small-integer generator function have uniform distribution.

The function should take as arguments:

The function should produce:

Show the distribution checker working when the produced distribution is flat enough and when it is not. (Use a generator from Seven-sided dice from five-sided dice).

See also:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Verify distribution uniformity/Naive step by step in the Nim programming language

Source code in the nim programming language

import tables


proc checkDist(f: proc(): int; repeat: Positive; tolerance: float) =

  var counts: CountTable[int]
  for _ in 1..repeat:
    counts.inc f()

  let expected = (repeat / counts.len).toInt    # Rounded to nearest.
  let allowedDelta = (expected.toFloat * tolerance / 100).toInt
  var maxDelta = 0
  for val, count in counts.pairs:
    let d = abs(count - expected)
    if d > maxDelta: maxDelta = d
    
  let status = if maxDelta <= allowedDelta: "passed" else: "failed"
  echo "Checking ", repeat, " values with a tolerance of ", tolerance, "%."
  echo "Random generator ", status, " the uniformity test."
  echo "Max delta encountered = ", maxDelta, "   Allowed delta = ", allowedDelta


when isMainModule:
  import random
  randomize()
  proc rand5(): int = rand(1..5)
  checkDist(rand5, 1_000_000, 0.5)


  

You may also check:How to resolve the algorithm Delete a file step by step in the Aime programming language
You may also check:How to resolve the algorithm Mandelbrot set step by step in the Maxima programming language
You may also check:How to resolve the algorithm Walk a directory/Recursively step by step in the Prolog programming language
You may also check:How to resolve the algorithm Chowla numbers step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the Pointless programming language