Statistics/Normal distribution: Difference between revisions

(Add R implementation)
(→‎{{header|Tcl}}: added zkl)
Line 1,851:
</pre>
The blank lines in the output are where the number of samples is too small to even merit a single unit on the histogram.
 
=={{header|zkl}}==
{{trans|Go}}
<lang zkl>fcn norm2{ // Box-Muller
const PI2=(0.0).pi*2;;
rnd:=(0.0).random.fp(1); // random number in [0,1), using partial application
r,a:=(-2.0*rnd().log()).sqrt(), PI2*rnd();
return(r*a.cos(), r*a.sin()); // z0,z1
}
const N=100000, BINS=12, SIG=3, SCALE=500;
var sum=0.0,sumSq=0.0, h=BINS.pump(List(),0); // (0,0,0,...)
fcn accum(v){
sum+=v;
sumSq+=v*v;
b:=(v + SIG)*BINS/SIG/2;
if(0<=b<BINS) h[b]+=1;
};</lang>
Partial application: rnd() --> (0.0).random(1). Basically, the fp method fixes the call parameters, which are then used when the partial thing is run.
<lang zkl>foreach i in (N/2){ v1,v2:=norm2(); accum(v1); accum(v2); }
println("Samples: %,d".fmt(N));
println("Mean: ", m:=sum/N);
println("Stddev: ", (sumSq/N - m*m).sqrt());
foreach p in (h){ println("*"*(p/SCALE)) }</lang>
{{out}}
<pre>
Samples: 100,000
Mean: 0.0005999
Stddev: 1.003
*
***
********
******************
*****************************
**************************************
**************************************
*****************************
******************
********
***
*
</pre>
Anonymous user