How to resolve the algorithm Benford's law step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Benford's law step by step in the Nim programming language

Table of Contents

Problem Statement

Benford's law, also called the first-digit law, refers to the frequency distribution of digits in many (but not all) real-life sources of data. In this distribution, the number 1 occurs as the first digit about 30% of the time, while larger numbers occur in that position less frequently: 9 as the first digit less than 5% of the time. This distribution of first digits is the same as the widths of gridlines on a logarithmic scale. Benford's law also concerns the expected distribution for digits beyond the first, which approach a uniform distribution. This result has been found to apply to a wide variety of data sets, including electricity bills, street addresses, stock prices, population numbers, death rates, lengths of rivers, physical and mathematical constants, and processes described by power laws (which are very common in nature). It tends to be most accurate when values are distributed across multiple orders of magnitude. A set of numbers is said to satisfy Benford's law if the leading digit

d

{\displaystyle d}

(

d ∈ { 1 , … , 9 }

{\displaystyle d\in {1,\ldots ,9}}

) occurs with probability For this task, write (a) routine(s) to calculate the distribution of first significant (non-zero) digits in a collection of numbers, then display the actual vs. expected distribution in the way most convenient for your language (table / graph / histogram / whatever). Use the first 1000 numbers from the Fibonacci sequence as your data set. No need to show how the Fibonacci numbers are obtained. You can generate them or load them from a file; whichever is easiest. Display your actual vs expected distribution.

For extra credit: Show the distribution for one other set of numbers from a page on Wikipedia. State which Wikipedia page it can be obtained from and what the set enumerates. Again, no need to display the actual list of numbers or the code to load them.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Benford's law step by step in the Nim programming language

Source code in the nim programming language

import math
import strformat

type

  # Non zero digit range.
  Digit = range[1..9]

  # Count array used to compute a distribution.
  Count = array[Digit, Natural]

  # Array to store frequencies.
  Distribution = array[Digit, float]


####################################################################################################
# Fibonacci numbers generation.

import bignum

proc fib(count: int): seq[Int] =
  ## Build a sequence of "count auccessive Finonacci numbers.
  result.setLen(count)
  result[0..1] = @[newInt(1), newInt(1)]
  for i in 2..<count:
    result[i] = result[i-1] + result[i-2]


####################################################################################################
# Benford distribution.

proc benfordDistrib(): Distribution =
  ## Compute Benford distribution.

  for d in 1..9:
    result[d] = log10(1 + 1 / d)

const BenfordDist = benfordDistrib()

#---------------------------------------------------------------------------------------------------

template firstDigit(n: Int): Digit =
  # Return the first (non null) digit of "n".
  ord(($n)[0]) - ord('0')

#---------------------------------------------------------------------------------------------------

proc actualDistrib(s: openArray[Int]): Distribution =
  ## Compute actual distribution of first digit.
  ## Null values are ignored.

  var counts: Count
  for val in s:
    if not val.isZero():
      inc counts[val.firstDigit()]

  let total = sum(counts)
  for d in 1..9:
    result[d] = counts[d] / total

#---------------------------------------------------------------------------------------------------

proc display(distrib: Distribution) =
  ## Display an actual distribution versus the Benford reference distribution.

  echo "d   actual   expected"
  echo "---------------------"
  for d in 1..9:
    echo fmt"{d}   {distrib[d]:6.4f}    {BenfordDist[d]:6.4f}"


#———————————————————————————————————————————————————————————————————————————————————————————————————

let fibSeq = fib(1000)
let distrib = actualDistrib(fibSeq)
echo "Fibonacci numbers first digit distribution:\n"
distrib.display()


  

You may also check:How to resolve the algorithm Show the epoch step by step in the Rust programming language
You may also check:How to resolve the algorithm Count in factors step by step in the Raku programming language
You may also check:How to resolve the algorithm Twin primes step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Consecutive primes with ascending or descending differences step by step in the REXX programming language
You may also check:How to resolve the algorithm Letter frequency step by step in the Icon and Unicon programming language