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

Published on 12 May 2024 09:40 PM

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

Source code in the swift programming language

import Foundation

/* Reads from a file and returns the content as a String */
func readFromFile(fileName file:String) -> String{
    
    var ret:String = ""
    
    let path = Foundation.URL(string: "file://"+file)
    
    do {
        ret = try String(contentsOf: path!, encoding: String.Encoding.utf8)
    }
    catch {
        print("Could not read from file!")
        exit(-1)
    }
   
    return ret
}

/* Calculates the probability following Benford's law */
func benford(digit z:Int) -> Double {
    
    if z<=0 || z>9 {
        perror("Argument must be between 1 and 9.")
        return 0
    }
    
    return log10(Double(1)+Double(1)/Double(z))
}

// get CLI input
if CommandLine.arguments.count < 2 {
    print("Usage: Benford [FILE]")
    exit(-1)
}

let pathToFile = CommandLine.arguments[1]

// Read from given file and parse into lines
let content = readFromFile(fileName: pathToFile)
let lines = content.components(separatedBy: "\n")

var digitCount:UInt64 = 0
var countDigit:[UInt64] = [0,0,0,0,0,0,0,0,0]

// check digits line by line
for line in lines {
    if line == "" {
        continue
    }
    let charLine = Array(line.characters)
        switch(charLine[0]){
            case "1":
                countDigit[0] += 1
                digitCount += 1
                break
            case "2":
                countDigit[1] += 1
                digitCount += 1
                break
            case "3":
                countDigit[2] += 1
                digitCount += 1
                break
            case "4":
                countDigit[3] += 1
                digitCount += 1
                break
            case "5":
                countDigit[4] += 1
                digitCount += 1
                break
            case "6":
                countDigit[5] += 1
                digitCount += 1
                break
            case "7":
                countDigit[6] += 1
                digitCount += 1
                break
            case "8":
                countDigit[7] += 1
                digitCount += 1
                break
            case "9":
                countDigit[8] += 1
                digitCount += 1
                break
            default:
                break
        }
    
}

// print result
print("Digit\tBenford [%]\tObserved [%]\tDeviation")
print("~~~~~\t~~~~~~~~~~~~\t~~~~~~~~~~~~\t~~~~~~~~~")
for i in 0..<9 {
    let temp:Double = Double(countDigit[i])/Double(digitCount)
    let ben = benford(digit: i+1)
    print(String(format: "%d\t%.2f\t\t%.2f\t\t%.4f", i+1,ben*100,temp*100,ben-temp))
}


  

You may also check:How to resolve the algorithm Continued fraction step by step in the NetRexx programming language
You may also check:How to resolve the algorithm Mutex step by step in the C programming language
You may also check:How to resolve the algorithm Terminal control/Inverse video step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the 360 Assembly programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the PureBasic programming language