Average loop length: Difference between revisions

Average loop length en FreeBasic
(Replaced "strfmt" by "strformat" which is now equivalent but standard. Replaced the deprecated "random(n)" by "rand(n - 1)".)
(Average loop length en FreeBasic)
Line 850:
20 5.2927 5.2936 -0.017%
</pre>
 
 
=={{header|FreeBASIC}}==
<lang freebasic>Const max_N = 20, max_ciclos = 1000000
 
Function Factorial(Byval N As Integer) As Double
Dim As Double d: d = 1
If N = 0 Then Factorial = 1: Exit Function
While (N > 1)
d *= N
N -= 1
Wend
Factorial = d
End Function
 
Function Analytical(N As Integer) As Double
Dim As Double i, sum = 0
For i = 1 To N
sum += Factorial(N) / N^i / Factorial(N-i)
Next i
Return sum
End Function
 
Function Average(N As Integer, ciclos As Double) As Double
Dim As Integer i, x, bits, sum = 0
For i = 0 To ciclos - 1
x = 1 : bits = 0
While (bits And x) = 0
sum += 1
bits Or= x
x = 1 Shl (Rnd * (N - 1))
Wend
Next i
Return sum / ciclos
End Function
 
Randomize Timer
Print " N promedio analitico (error)"
Print "--- ---------- ----------- ----------"
For N As Integer = 1 To max_N
Dim As Double avg = Average(N, max_ciclos)
Dim As Double ana = Analytical(N)
Dim As Double diff = abs(avg-ana) / ana * 100
Print Using " ## #####.###0 #####.###0 ###.#0%"; N; avg; ana; diff
Next N
Sleep
</lang>
 
 
=={{header|Go}}==
2,148

edits