Java Reference
In-Depth Information
Notice that instead of tallying n in the body of the loop, we are instead tallying
firstDigit(n) (just the first digit, not the entire number).
The value 0 presents a potential problem for us. Benford's Law is meant to apply
to data that comes from an exponential sequence. But even if you are increasing
exponentially, if you start with 0 , you never get beyond 0 . As a result, it is best to
eliminate the 0 values from the calculation. Often they won't occur at all.
When reporting results, then, let's begin by reporting the excluded zeros if they
exist:
if (count[0] > 0) {
System.out.println("excluding " + count[0] + " zeros");
}
For the other digits, we want to report the number of occurrences of each and also
the percentage of each. To figure the percentage, we'll need to know the sum of the
values. This is a good place to introduce a method that finds the sum of an array of
integers. It's a fairly straightforward array traversal problem that can be solved with a
for-each loop:
public static int sum(int[] data) {
int sum = 0;
for (int n : data) {
sum += n;
}
return sum;
}
Now we can compute the total number of digits by calling the method and sub-
tracting the number of 0 s:
int total = sum(count) - count[0];
And once we have the total number of digits, we can write a loop to report each of
the percentages. To compute the percentages, we multiply each count by 100 and divide
by the total number of digits. We have to be careful to multiply by 100.0 rather than
100 to make sure that we are computing the result using double values. Otherwise
we'll get truncated integer division and won't get any digits after the decimal point:
for (int i = 1; i < count.length; i++) {
double pct = count[i] * 100.0 / total;
System.out.println(i + " " + count[i] + " " + pct);
}
Notice that the loop starts at 1 instead of 0 because we have excluded the zeros
from our reporting.
Search WWH ::




Custom Search