September 2017 Update
This commit is contained in:
parent
bba7bfd280
commit
ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions
|
|
@ -1,51 +1,56 @@
|
|||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.Random;
|
||||
import java.util.Set;
|
||||
|
||||
public class AverageLoopLength {
|
||||
private static final int N = 100000;
|
||||
//analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i)
|
||||
public static float analytical(int n){
|
||||
float[] factorial = new float[n+1];
|
||||
float[] powers = new float[n+1];
|
||||
factorial[0] = powers[0] = 1;
|
||||
for(int i=1;i<=n;i++){
|
||||
factorial[i] = factorial[i-1] * i;
|
||||
powers[i] = powers[i-1] * n;
|
||||
}
|
||||
float sum = 0;
|
||||
//memoized factorial and powers
|
||||
for(int i=1;i<=n;i++){
|
||||
sum += factorial[n]/factorial[n-i]/powers[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
public static float average(int n){
|
||||
float sum = 0;
|
||||
for(int a=0;a<N;a++){
|
||||
int[] random = new int[n];
|
||||
for(int i=0;i<n;i++){
|
||||
random[i] = (int)(Math.random()*n);
|
||||
}
|
||||
ArrayList<Integer> seen = new ArrayList<>(n);
|
||||
int current = 0;
|
||||
int length = 0;
|
||||
while(true){
|
||||
length++;
|
||||
seen.add(current);
|
||||
current = random[current];
|
||||
if(seen.contains(current)){
|
||||
break;
|
||||
}
|
||||
}
|
||||
sum += length;
|
||||
}
|
||||
return sum/N;
|
||||
}
|
||||
public static void main(String args[]){
|
||||
System.out.println(" N average analytical (error)\n=== ========= ============ =========");
|
||||
for(int i=1;i<=20;i++){
|
||||
float avg = average(i);
|
||||
float ana = analytical(i);
|
||||
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)",i,avg,ana,((ana-avg)/ana*100)));;
|
||||
}
|
||||
}
|
||||
|
||||
private static final int N = 100000;
|
||||
|
||||
//analytical(n) = sum_(i=1)^n (n!/(n-i)!/n**i)
|
||||
private static double analytical(int n) {
|
||||
double[] factorial = new double[n + 1];
|
||||
double[] powers = new double[n + 1];
|
||||
powers[0] = 1.0;
|
||||
factorial[0] = 1.0;
|
||||
for (int i = 1; i <= n; i++) {
|
||||
factorial[i] = factorial[i - 1] * i;
|
||||
powers[i] = powers[i - 1] * n;
|
||||
}
|
||||
double sum = 0;
|
||||
//memoized factorial and powers
|
||||
for (int i = 1; i <= n; i++) {
|
||||
sum += factorial[n] / factorial[n - i] / powers[i];
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
private static double average(int n) {
|
||||
Random rnd = new Random();
|
||||
double sum = 0.0;
|
||||
for (int a = 0; a < N; a++) {
|
||||
int[] random = new int[n];
|
||||
for (int i = 0; i < n; i++) {
|
||||
random[i] = rnd.nextInt(n);
|
||||
}
|
||||
Set<Integer> seen = new HashSet<>(n);
|
||||
int current = 0;
|
||||
int length = 0;
|
||||
while (seen.add(current)) {
|
||||
length++;
|
||||
current = random[current];
|
||||
}
|
||||
sum += length;
|
||||
}
|
||||
return sum / N;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println(" N average analytical (error)");
|
||||
System.out.println("=== ========= ============ =========");
|
||||
for (int i = 1; i <= 20; i++) {
|
||||
double avg = average(i);
|
||||
double ana = analytical(i);
|
||||
System.out.println(String.format("%3d %9.4f %12.4f (%6.2f%%)", i, avg, ana, ((ana - avg) / ana * 100)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
27
Task/Average-loop-length/Julia/average-loop-length.julia
Normal file
27
Task/Average-loop-length/Julia/average-loop-length.julia
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# Version 5.2
|
||||
analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n)
|
||||
|
||||
function test(n::Integer, times::Integer = 1000000)
|
||||
c = 0
|
||||
for i = range(0, times)
|
||||
x, bits = 1, 0
|
||||
while (bits & x) == 0
|
||||
c += 1
|
||||
bits |= x
|
||||
x = 1 << rand(0:(n - 1))
|
||||
end
|
||||
end
|
||||
return c / times
|
||||
end
|
||||
|
||||
function main(n::Integer)
|
||||
println(" n\tavg\texp.\tdiff\n-------------------------------")
|
||||
for n in 1:n
|
||||
avg = test(n)
|
||||
theory = analytical(n)
|
||||
diff = (avg / theory - 1) * 100
|
||||
@printf(STDOUT, "%2d %8.4f %8.4f %6.3f%%\n", n, avg, theory, diff)
|
||||
end
|
||||
end
|
||||
|
||||
main(20)
|
||||
38
Task/Average-loop-length/Kotlin/average-loop-length.kotlin
Normal file
38
Task/Average-loop-length/Kotlin/average-loop-length.kotlin
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
const val NMAX = 20
|
||||
const val TESTS = 1000000
|
||||
val rand = java.util.Random()
|
||||
|
||||
fun avg(n: Int): Double {
|
||||
var sum = 0
|
||||
for (t in 0 until TESTS) {
|
||||
val v = BooleanArray(NMAX)
|
||||
var x = 0
|
||||
while (!v[x]) {
|
||||
v[x] = true
|
||||
sum++
|
||||
x = rand.nextInt(n)
|
||||
}
|
||||
}
|
||||
return sum.toDouble() / TESTS
|
||||
}
|
||||
|
||||
fun ana(n: Int): Double {
|
||||
val nn = n.toDouble()
|
||||
var term = 1.0
|
||||
var sum = 1.0
|
||||
for (i in n - 1 downTo 1) {
|
||||
term *= i / nn
|
||||
sum += term
|
||||
}
|
||||
return sum
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
println(" N average analytical (error)")
|
||||
println("=== ========= ============ =========")
|
||||
for (n in 1..NMAX) {
|
||||
val a = avg(n)
|
||||
val b = ana(n)
|
||||
println(String.format("%3d %6.4f %10.4f (%4.2f%%)", n, a, b, Math.abs(a - b) / b * 100.0))
|
||||
}
|
||||
}
|
||||
|
|
@ -1,20 +1,20 @@
|
|||
import math, strfmt
|
||||
import random, math, strfmt
|
||||
randomize()
|
||||
|
||||
const
|
||||
maxN = 20
|
||||
times = 1_000_000
|
||||
|
||||
proc factorial(n): float =
|
||||
proc factorial(n: int): float =
|
||||
result = 1
|
||||
for i in 1 .. n:
|
||||
result *= i.float
|
||||
|
||||
proc expected(n): float =
|
||||
proc expected(n: int): float =
|
||||
for i in 1 .. n:
|
||||
result += factorial(n) / pow(n.float, i.float) / factorial(n - i)
|
||||
|
||||
proc test(n, times): int =
|
||||
proc test(n, times: int): int =
|
||||
for i in 1 .. times:
|
||||
var
|
||||
x = 1
|
||||
|
|
|
|||
|
|
@ -3,34 +3,34 @@ parse arg runs tests seed . /*obtain optional arguments fro
|
|||
if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/
|
||||
if tests =='' | tests =="," then tests= 1000000 /* " " " " " " */
|
||||
if datatype(seed,'W') then call random ,, seed /*Is integer? For RAND repeatability.*/
|
||||
!.=0; !.0=1 /*used for factorial (!) memoization.*/
|
||||
!.=0; !.0=1 /*used for factorial (!) memoization.*/
|
||||
numeric digits 100000 /*be able to calculate 25k! if need be.*/
|
||||
numeric digits max(9, length( !(runs) ) ) /*set the NUMERIC DIGITS for !(runs). */
|
||||
say right( runs, 24) 'runs' /*display number of runs we're using.*/
|
||||
say right( tests, 24) 'tests' /* " " " tests " " */
|
||||
say right( digits(), 24) 'digits' /* " " " digits " " */
|
||||
say right( runs, 24) 'runs' /*display number of runs we're using.*/
|
||||
say right( tests, 24) 'tests' /* " " " tests " " */
|
||||
say right( digits(), 24) 'digits' /* " " " digits " " */
|
||||
say
|
||||
say " N average exact % error " /* ◄─── title, header ►────────┐ */
|
||||
hdr=" ═══ ═════════ ═════════ ═════════"; pad=left('',3) /* ◄────────┘ */
|
||||
say hdr
|
||||
do #=1 for runs; av=fmtD(exact(#)) /*use four digits past decimal point. */
|
||||
xa=fmtD(exper(#)) /* " " " " " " */
|
||||
say right(#,9) pad xa pad av pad fmtD(abs(xa-av)*100/av) /*display values.*/
|
||||
do #=1 for runs; av=fmtD( exact(#) ) /*use four digits past decimal point. */
|
||||
xa=fmtD( exper(#) ) /* " " " " " " */
|
||||
say right(#,9) pad xa pad av pad fmtD( abs(xa-av) * 100 / av) /*show values.*/
|
||||
end /*#*/
|
||||
say hdr /*display the final header (some bars).*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
!: procedure expose !.; parse arg z; if !.z\==0 then return !.z
|
||||
!=1; do j=2 for z-1; !=!*j; !.j=!; end; /*factorial*/ return !
|
||||
!=1; do j=2 for z -1; !=!*j; !.j=!; end; /*compute factorial*/ return !
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
exact: parse arg x; s=0; do j=1 for x; s=s+!(x)/!(x-j)/x**j; end; return s
|
||||
exact: parse arg x; s=0; do j=1 for x; s=s + !(x) / !(x-j) / x**j; end; return s
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
exper: parse arg n; k=0; do tests; $.=0 /*do it TESTS times.*/
|
||||
do n; r=random(1,n); if $.r then leave
|
||||
$.r=1; k=k+1 /*bump the counter. */
|
||||
exper: parse arg n; k=0; do tests; $.=0 /*do it TESTS times.*/
|
||||
do n; r=random(1, n); if $.r then leave
|
||||
$.r=1; k=k + 1 /*bump the counter. */
|
||||
end /*n*/
|
||||
end /*tests*/
|
||||
return k/tests
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
fmtD: parse arg y,d; d=word(d 4,1); y=format(y,,d); parse var y w '.' f
|
||||
if f=0 then return w || left('', d+1); return y
|
||||
fmtD: parse arg y,d; d=word(d 4, 1); y=format(y, , d); parse var y w '.' f
|
||||
if f=0 then return w || left('', d +1); return y
|
||||
|
|
|
|||
56
Task/Average-loop-length/Scheme/average-loop-length.ss
Normal file
56
Task/Average-loop-length/Scheme/average-loop-length.ss
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
(import (scheme base)
|
||||
(scheme write)
|
||||
(srfi 1 lists)
|
||||
(only (srfi 13 strings) string-pad-right)
|
||||
(srfi 27 random-bits))
|
||||
|
||||
(define (analytical-function n)
|
||||
(define (factorial n)
|
||||
(fold * 1 (iota n 1)))
|
||||
;
|
||||
(fold (lambda (i sum)
|
||||
(+ sum
|
||||
(/ (factorial n) (expt n i) (factorial (- n i)))))
|
||||
0
|
||||
(iota n 1)))
|
||||
|
||||
(define (simulation n runs)
|
||||
(define (single-simulation)
|
||||
(random-source-randomize! default-random-source)
|
||||
(let ((vec (make-vector n #f)))
|
||||
(let loop ((count 0)
|
||||
(num (random-integer n)))
|
||||
(if (vector-ref vec num)
|
||||
count
|
||||
(begin (vector-set! vec num #t)
|
||||
(loop (+ 1 count)
|
||||
(random-integer n)))))))
|
||||
;;
|
||||
(let loop ((total 0)
|
||||
(run runs))
|
||||
(if (zero? run)
|
||||
(/ total runs)
|
||||
(loop (+ total (single-simulation))
|
||||
(- run 1)))))
|
||||
|
||||
(display " N average formula (error) \n")
|
||||
(display "=== ========= ========= =========\n")
|
||||
(for-each
|
||||
(lambda (n)
|
||||
(let ((simulation (inexact (simulation n 10000)))
|
||||
(formula (inexact (analytical-function n))))
|
||||
(display
|
||||
(string-append
|
||||
" "
|
||||
(string-pad-right (number->string n) 3)
|
||||
" "
|
||||
(string-pad-right (number->string simulation) 6)
|
||||
" "
|
||||
(string-pad-right (number->string formula) 6)
|
||||
" ("
|
||||
(string-pad-right
|
||||
(number->string (* 100 (/ (- simulation formula) formula)))
|
||||
5)
|
||||
"%)"))
|
||||
(newline)))
|
||||
(iota 20 1))
|
||||
33
Task/Average-loop-length/Zkl/average-loop-length.zkl
Normal file
33
Task/Average-loop-length/Zkl/average-loop-length.zkl
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
const N=20;
|
||||
|
||||
(" N average analytical (error)").println();
|
||||
("=== ========= ============ =========").println();
|
||||
foreach n in ([1..N]){
|
||||
a := avg(n);
|
||||
b := ana(n);
|
||||
"%3d %9.4f %12.4f (%6.2f%%)".fmt(
|
||||
n, a, b, ((a-b)/b*100)).println();
|
||||
}
|
||||
|
||||
fcn f(n){ (0).random(n) }
|
||||
|
||||
fcn avg(n){
|
||||
tests := 0d10_000;
|
||||
sum := 0;
|
||||
do(tests){
|
||||
v:=(0).pump(n,List,T(Void,False)).copy();
|
||||
while(1){
|
||||
z := f(n);
|
||||
if(v[z]) break;
|
||||
v[z] = True;
|
||||
sum += 1;
|
||||
}
|
||||
}
|
||||
return(sum.toFloat() / tests);
|
||||
}
|
||||
|
||||
fcn fact(n) { (1).reduce(n,fcn(N,n){N*n},1.0) } //-->Float
|
||||
fcn ana(n){
|
||||
n=n.toFloat();
|
||||
(1).reduce(n,'wrap(sum,i){ sum+fact(n)/n.pow(i)/fact(n-i) },0.0);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue