Basic

func generate_statistics(n) {
    var(sum=0, sum2=0)
    var hist = 10.of(0)
 
    n.times {
        var r = 1.rand
        sum += r
        sum2 += r**2
        hist[10*r] += 1
    }
 
    var mean = sum/n
    var stddev = sqrt(sum2/n - mean**2)
 
    say "size: #{n}"
    say "mean:   #{mean}"
    say "stddev: #{stddev}"
 
    var max = hist.max
    for i in ^hist {
        printf("%.1f:%s\n", 0.1*i, "=" * 70*hist[i]/max)
    }
    print "\n"
}
 
[100, 1000, 10000].each {|n| generate_statistics(n) }

Output:

size: 100
mean:   0.4585051431752446588
stddev: 0.2870559459562831101619581273667538623484
0.0:=================================================================
0.1:==================================================
0.2:======================================================================
0.3:=============================================
0.4:=======================================================
0.5:==============================
0.6:==================================================
0.7:==================================================
0.8:==================================================
0.9:===================================

size: 1000
mean:   0.51292239343467439552
stddev: 0.2832968595790956540009121237087699143503
0.0:===================================================
0.1:========================================================
0.2:========================================================
0.3:========================================================
0.4:======================================================================
0.5:==================================================================
0.6:===============================================================
0.7:=========================================================
0.8:========================================================
0.9:====================================================================

size: 10000
mean:   0.49883638025449614521145
stddev: 0.2898083000452161646017460189689302069547
0.0:====================================================================
0.1:============================================================
0.2:======================================================================
0.3:==============================================================
0.4:===============================================================
0.5:=================================================================
0.6:===============================================================
0.7:=================================================================
0.8:==================================================================
0.9:===============================================================

Last updated