Average loop length: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 1,035:
Sleep
</lang>
 
 
=={{header|FutureBasic}}==
<lang futurebasic>
_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 or 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 @"\nNumber of tests performed: %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
</lang>
{{output}}
<pre>
Number of tests performed: 1000000
 
N Average Analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 0.0001%
2 1.4999 1.5000 -0.0070%
3 1.8877 1.8889 -0.0630%
4 2.2187 2.2188 -0.0011%
5 2.5102 2.5104 -0.0065%
6 2.7735 2.7747 -0.0438%
7 3.0173 3.0181 -0.0273%
8 3.2478 3.2450 0.0854%
9 3.4569 3.4583 -0.0424%
10 3.6604 3.6602 0.0060%
11 3.8506 3.8524 -0.0449%
12 4.0361 4.0361 0.0003%
13 4.2148 4.2123 0.0582%
14 4.3845 4.3820 0.0559%
15 4.5454 4.5458 -0.0079%
16 4.7056 4.7043 0.0288%
17 4.8558 4.8579 -0.0428%
18 5.0143 5.0071 0.1450%
19 5.1509 5.1522 -0.0254%
20 5.2985 5.2936 0.0929%
</pre>
 
 
 
719

edits