Average loop length: Difference between revisions

no edit summary
No edit summary
Line 3,241:
19 5.1518 5.1522 ( 0.0001%)
20 5.2906 5.2936 ( 0.0006%)
</pre>
 
=={{header|Vlang}}==
{{trans|Go}}
<lang vlang>import rand
import math
 
const nmax = 20
fn main() {
println(" N average analytical (error)")
println("=== ========= ============ =========")
for n := 1; n <= nmax; n++ {
a := avg(n)
b := ana(n)
println("${n:3} ${a:9.4f} ${b:12.4f} (${math.abs(a-b)/b*100:6.2f}%)" )
}
}
fn avg(n int) f64 {
tests := int(1e4)
mut sum := 0
for _ in 0..tests {
mut v := [nmax]bool{}
for x := 0; !v[x]; {
v[x] = true
sum++
x = rand.intn(n) or {0}
}
}
return f64(sum) / tests
}
fn ana(n int) f64 {
nn := f64(n)
mut term := 1.0
mut sum := 1.0
for i := nn - 1; i >= 1; i-- {
term *= i / nn
sum += term
}
return sum
}</lang>
 
{{out}}
Sample output:
<pre>
N average analytical (error)
=== ========= ============ =========
1 1.0000 1.0000 ( 0.00%)
2 1.4967 1.5000 ( 0.22%)
3 1.8970 1.8889 ( 0.43%)
4 2.2151 2.2188 ( 0.16%)
5 2.5044 2.5104 ( 0.24%)
6 2.7884 2.7747 ( 0.49%)
7 3.0356 3.0181 ( 0.58%)
8 3.2468 3.2450 ( 0.05%)
9 3.4692 3.4583 ( 0.31%)
10 3.6538 3.6602 ( 0.18%)
11 3.8325 3.8524 ( 0.52%)
12 4.0674 4.0361 ( 0.78%)
13 4.2199 4.2123 ( 0.18%)
14 4.3808 4.3820 ( 0.03%)
15 4.5397 4.5458 ( 0.13%)
16 4.6880 4.7043 ( 0.35%)
17 4.8554 4.8579 ( 0.05%)
18 5.0311 5.0071 ( 0.48%)
19 5.1577 5.1522 ( 0.11%)
20 5.2995 5.2936 ( 0.11%)
</pre>
 
338

edits