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

Published on 22 June 2024 08:30 PM

How to resolve the algorithm Benford's law step by step in the Kotlin 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 Kotlin programming language

Kotlin Code Overview

This Kotlin code demonstrates the concept of Benford's law, which analyzes the distribution of the first digit in a set of numbers. It uses a NumberGenerator interface to generate a sequence of numbers and then applies Benford's analysis to the first digits of these numbers.

NumberGenerator Interface:

The NumberGenerator interface defines a single property numbers, which is an array of BigInteger numbers. This interface is used to abstract the number generation process from the Benford analysis logic.

Benford Class:

The Benford class implements the logic for Benford's analysis. It takes a NumberGenerator object as an argument and analyzes the first digits of the numbers generated by that generator.

  • Initialization:

    • Initializes an integer array firstDigits to store the count of occurrences of each first digit.
    • Calculates the count as the total number of numbers generated by the NumberGenerator.
    • Builds the str string for displaying the analysis results.
  • Analysis:

    • Iterates over each number in the numbers array generated by the NumberGenerator.
    • Increments the count for the first digit of each number in the firstDigits array.

FibonacciGenerator Object:

The FibonacciGenerator object implements the NumberGenerator interface and provides a lazy-initialized array of Fibonacci numbers as the numbers property.

Main Function:

  • Creates a FibonacciGenerator object as the argument to the Benford constructor.
  • Prints the string representation of the Benford object, which displays the distribution of the first digits according to Benford's law.

Output:

The output of the program is a table that shows:

  • First digit: Values from 1 to 9
  • Frequency: Frequency of occurrence of each first digit as a percentage of the total numbers
  • Logarithm: Logarithmic value of the probability of each first digit occurring according to Benford's law

Source code in the kotlin programming language

import java.math.BigInteger

interface NumberGenerator {
    val numbers: Array<BigInteger>
}

class Benford(ng: NumberGenerator) {
    override fun toString() = str

    private val firstDigits = IntArray(9)
    private val count = ng.numbers.size.toDouble()
    private val str: String

    init {
        for (n in ng.numbers) {
            firstDigits[n.toString().substring(0, 1).toInt() - 1]++
        }

        str = with(StringBuilder()) {
            for (i in firstDigits.indices) {
                append(i + 1).append('\t').append(firstDigits[i] / count)
                append('\t').append(Math.log10(1 + 1.0 / (i + 1))).append('\n')
            }

            toString()
        }
    }
}

object FibonacciGenerator : NumberGenerator {
    override val numbers: Array<BigInteger> by lazy {
        val fib = Array<BigInteger>(1000, { BigInteger.ONE })
        for (i in 2 until fib.size)
            fib[i] = fib[i - 2].add(fib[i - 1])
        fib
    }
}

fun main(a: Array<String>) = println(Benford(FibonacciGenerator))


  

You may also check:How to resolve the algorithm Monty Hall problem step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Increment a numerical string step by step in the Lasso programming language
You may also check:How to resolve the algorithm Prime conspiracy step by step in the Factor programming language
You may also check:How to resolve the algorithm Largest proper divisor of n step by step in the TI-57 programming language
You may also check:How to resolve the algorithm Kronecker product based fractals step by step in the JavaScript programming language