Leading Digits Of Powers Of 2
June 23, 2017
John D. Cook, a programmer who writes about mathematics (he would probably describe himself as a mathematician who writes about programming) recently wrote about the distribution of the leading digits of the powers of 2, observing that they follow Benford’s Law, which we studied in a previous exercise.
Your task is to write a program that demonstrates that the distribution of the leading digits of the powers of 2 follows Benford’s Law. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
In Python
I looked at when the fractional part of the power begins to look useless in 64-bit floating point, then generated random samples of one million powers with a 32-bit exponent; those look ok. (In Julia.)
module Ben lead2(n) = first(k for k in 1:9 if mod(n * log10(2), 1) < log10(k + 1)) println("Floating-point fractional parts of log10(2^n) with n around ...") for p in [32, 40, 42, 50, 52, 60] m = one(UInt64) << p println("2^$(p): ", [mod(n * log10(2), 1) for n in (m - 4):(m + 4)]) end println() println("Sample distributions of 10^6 lead digits 1:9 of 2^n for 32-bit n") println("wanted: ", [Int(round(log10((k + 1)/k) * 10^6)) for k in 1:9]) for k in 1:3 sample = zeros(Int, 9) for exponent in rand(UInt32, 10^6) sample[lead2(exponent)] += 1 end println("sample: ", sample) end endUsing decimal in Python as indicated by Andrew Dalke in John Cook’s blog, the str operation is very fast. The code below needs about 1 second.
count = [0]*10 N = 1000000 a = decimal.Decimal(1) count[1] += 1 for i in range(N-1): a = a*2 count[int(str(a)[0])] += 1 print(count[1:]) # [301030, 176093, 124937, 96911, 79182, 66947, 57990, 51154, 45756]Solution in GNU bc:
v=1; t=1; max=100000 for (i=1;i<=max;++i) { if(length(v)>length(t)){t*=10;} count[v/t]+=1; v=v*2; } scale=4; for (i=1;i<10;++i) { print i, " : ", count[i], " ", count[i]/max*100, "%\n"; } quitWhich outputs: