Question
7.8 Benford's Law Summary: analyze input file to see if data follows Benford's law. Given a set of random positive integers, you would expect that
7.8 Benford's Law
Summary: analyze input file to see if data follows Benford's law.
Given a set of random positive integers, you would expect that 10% would start with a 1, 10% would start with a 2, and so on. The numbers should be evenly distributed across the 10 digits, right? Not so much...
Benfords law states that positive integers exhibit a certain behavior, if the numbers are truly random. For example, suppose the following numbers are collected at random (the -1 at the end denotes the end of the input and is not considered part of the data):
0123
22184
123456
9811
7812
123
12345
51613
2239
-1
Benford's law states that approximately 31% of the numbers will start with the digit '1'. In the example above, there are a total of 9 inputs, and 3 start with a '1' --- that's 3/9 or 33%, which would follow Benford's law. You can read more about Benford's law on Wikipedia. A practical application of Benford's law is the detection of fraud. Benford's law holds in practice when analyzing random sets of positive integers.
Write a complete C++ program that inputs a filename from the keyboard, and then opens and inputs N>0 integers from that file. The program counts how many of these integers start with the digit '0', the digit '1', the digit '2', ..., and the digit '9'. After inputting all the data, the program outputs the percentages of numbers that started with each digit. For example, suppose the file "test01.txt" contains the following integers:
0123
22184
123456
9811
7812
123
12345
51613
2239
-1
If your program is given the following input
test01.txt
It should open and analyze this file, and yield the following output:
test01.txt N=9 0's: 1, 11.1111% 1's: 3, 33.3333% 2's: 2, 22.2222% 3's: 0, 0% 4's: 0, 0% 5's: 1, 11.1111% 6's: 0, 0% 7's: 1, 11.1111% 8's: 0, 0% 9's: 1, 11.1111%
Hint: do NOT input the data as integers. Since you need to look at the first digit only, it is much easier if you input each value as a string, and then access the first digit using array notation [0]:
string s; file >> s; if (s[0] == '0') // s starts with the digit 0:
This implies the while loop repeats until you see the string "-1", not the integer -1:
while (s != "-1")
#include
using namespace std;
int main() { string filename; ifstream file; // // Input the filename from the keyboard, then we'll open that file // to input the data for the program: // cin >> filename; cout << filename << endl; // TODO: read in data to see if it confirms to Benford's law. // return 0; }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started