Cumulative standard deviation: Difference between revisions

Content added Content deleted
No edit summary
Line 1,048: Line 1,048:
=={{header|Crystal}}==
=={{header|Crystal}}==
{{trans|Ruby}}
{{trans|Ruby}}
===Object===
===Using an object to keep state:===
<lang ruby>class StdDevAccumulator
<lang ruby>class StdDevAccumulator
def initialize
def initialize
Line 1,077: Line 1,077:
</pre>
</pre>


===Closure===
{{trans|Ruby}}
<lang ruby>def sdaccum
n, sum, sum2 = 0, 0.0, 0.0
->(num : Int32) do
n += 1
sum += num
sum2 += num**2
Math.sqrt( (sum2 * n - sum**2) / n**2 )
end
end

sd = sdaccum
[2,4,4,4,5,5,7,9].each {|n| print sd.call(n), ", "}</lang>
{{out}}
<pre>0.0, 1.0, 0.9428090415820634, 0.8660254037844386, 0.9797958971132712, 1.0, 1.3997084244475304, 2.0</pre>


=={{header|D}}==
=={{header|D}}==