RosettaCodeData/Task/Average-loop-length/FutureBasic/average-loop-length.basic

50 lines
977 B
Plaintext

_nmax = 20
_times = 1000000
local fn Average( n as long, times as long ) as double
long i, x
double b, c = 0
for i = 0 to times
x = 1 : b = 0
while ( b and x ) == 0
c++
b = b || x
x = 1 << ( rnd(n) - 1 )
wend
next
end fn = c / times
local fn Analyltic( n as long ) as double
double nn = (double)n
double term = 1.0
double sum = 1.0
long i
for i = nn - 1 to i >= 1 step -1
term = term * i / nn
sum = sum + term
next
end fn = sum
local fn DoIt
long n
double average, theory, difference
window 1
printf @"\nSamples tested: %ld\n", _times
print " N Average Analytical (error)"
print "=== ========= ============ ========="
for n = 1 to _nmax
average = fn Average( n, _times )
theory = fn Analyltic( n )
difference = ( average / theory - 1) * 100
printf @"%3d %9.4f %9.4f %10.4f%%", n, average, theory, difference
next
end fn
randomize
fn DoIt
HandleEvents