Benford's law: Difference between revisions
Content added Content deleted
(Added Fōrmulæ solution) |
|||
Line 505: | Line 505: | ||
</pre> |
</pre> |
||
=={{header|BCPL}}== |
|||
BCPL doesn't do floating point well, so I use integer math to compute the most significant digits of the Fibonacci sequence and use a table that has the values of log10(d + 1/d) |
|||
<lang BCPL> |
|||
GET "libhdr" |
|||
MANIFEST { |
|||
fib_sz = 1_000_000_000 // keep 9 significant digits for computing F(n) |
|||
} |
|||
LET msd(n) = VALOF { |
|||
UNTIL n < 10 DO |
|||
n /:= 10 |
|||
RESULTIS n |
|||
} |
|||
LET fibonacci(n, tally) BE { |
|||
LET a, b, c, e = 0, 1, ?, 0 |
|||
FOR i = 1 TO n { |
|||
TEST e = 0 |
|||
THEN tally[msd(b)] +:= 1 |
|||
ELSE tally[b / (fib_sz / 10)] +:= 1 |
|||
c := a + b |
|||
IF c > fib_sz { |
|||
a := a / 10 - (a MOD 10 >= 5) // subtract, since condition evalutes to |
|||
b := b / 10 - (b MOD 10 >= 5) // eithr 0 or -1. |
|||
c := a + b |
|||
e +:= 1 // keep track of exponent, just 'cuz |
|||
} |
|||
a, b := b, c |
|||
} |
|||
} |
|||
LET start() = VALOF { |
|||
// expected value of benford: log10(d + 1/d) |
|||
LET expected = TABLE 0, 301, 176, 125, 97, 79, 67, 58, 51, 46 |
|||
LET actual = VEC 9 |
|||
FOR i = 0 TO 9 DO actual!i := 0 |
|||
fibonacci(1000, actual) |
|||
writes("*nLeading digital distribution of the first 1,000 Fibonacci numbers*n") |
|||
writes("Digit*tActual*tExpected*n") |
|||
FOR i = 1 TO 9 |
|||
writef("%i *t%0.3d *t%0.3d *n", i, actual!i, expected!i) |
|||
RESULTIS 0 |
|||
} |
|||
</lang> |
|||
{{Out}} |
|||
<pre> |
|||
BCPL 64-bit Cintcode System (13 Jan 2020) |
|||
0.000> |
|||
Leading digital distribution of the first 1,000 Fibonacci numbers |
|||
Digit Actual Expected |
|||
1 0.301 0.301 |
|||
2 0.177 0.176 |
|||
3 0.125 0.125 |
|||
4 0.096 0.097 |
|||
5 0.080 0.079 |
|||
6 0.067 0.067 |
|||
7 0.056 0.058 |
|||
8 0.053 0.051 |
|||
9 0.045 0.046 |
|||
</pre> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
<lang c>#include <stdio.h> |
<lang c>#include <stdio.h> |