Average loop length: Difference between revisions

No edit summary
Line 3,164:
20 5,2958 5,2936 (0,041%)</pre>
 
=={{header|VBScript}}==
Ported from the VBA version
<lang vb>
Const MAX = 20
Const ITER = 100000
Function expected(n)
Dim sum
ni=n
For i = 1 To n
sum = sum + fact(n) / ni / fact(n-i)
ni=ni*n
Next
expected = sum
End Function
Function test(n )
Dim coun,x,bits
For i = 1 To ITER
x = 1
bits = 0
Do While Not bits And x
count = count + 1
bits = bits Or x
x = 2 ^ (Int(n * Rnd()))
Loop
Next
test = count / ITER
End Function
 
function rf(v,n,s) rf=right(string(n,s)& v,n):end function
dim fact(20)
fact(0)=1
for i=1 to 20 :fact(i)=i*fact(i-1): next
 
Dim n
Wscript.echo "For " & ITER &" iterations"
Wscript.Echo " n avg. exp. (error%)"
Wscript.Echo "== ====== ====== =========="
For n = 1 To MAX
av = test(n)
ex = expected(n)
Wscript.Echo rf(n,2," ")& " "& rf(formatnumber(av, 4),7," ") & " "& _
rf(formatnumber(ex,4),6," ")& " ("& rf(Formatnumber(1 - av / ex,4),7," ") & "%)"
Next
</lang>
Output
<pre>
For 100000 iterations
n avg. exp. (error%)
== ====== ====== ==========
1 1.0000 1.0000 ( 0.0000%)
2 1.4982 1.5000 ( 0.0012%)
3 1.8909 1.8889 (-0.0010%)
4 2.2190 2.2188 (-0.0001%)
5 2.5102 2.5104 ( 0.0001%)
6 2.7789 2.7747 (-0.0015%)
7 3.0230 3.0181 (-0.0016%)
8 3.2449 3.2450 ( 0.0000%)
9 3.4543 3.4583 ( 0.0012%)
10 3.6714 3.6602 (-0.0031%)
11 3.8559 3.8524 (-0.0009%)
12 4.0345 4.0361 ( 0.0004%)
13 4.2141 4.2123 (-0.0004%)
14 4.3762 4.3820 ( 0.0013%)
15 4.5510 4.5458 (-0.0011%)
16 4.6979 4.7043 ( 0.0014%)
17 4.8628 4.8579 (-0.0010%)
18 5.0081 5.0071 (-0.0002%)
19 5.1518 5.1522 ( 0.0001%)
20 5.2906 5.2936 ( 0.0006%)
</pre>
=={{header|Wren}}==
{{trans|Go}}