Cumulative standard deviation: Difference between revisions

Added two other solutions: one using an accumulator object, the other using a closure.
(→‎R: Added environment-based solution.)
(Added two other solutions: one using an accumulator object, the other using a closure.)
Line 2,503:
 
=={{header|Nim}}==
 
===Using global variables===
<lang nim>import math, strutils
 
var sdSum, sdSum2, sdN = 0.0
 
proc sd(x: float): float =
sdN += 1
sdSum += x
sdSum2 += x * x
sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN/ * sdN))
 
for value in [float 2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value.float), precision = -1)</lang>
 
for value in [2,4,4,4,5,5,7,9]:
echo value, " ", formatFloat(sd(value.float), precision = -1)</lang>
{{out}}
<pre>2 0
2 0
4 1
4 0.942809
Line 2,524 ⟶ 2,527:
7 1.39971
9 2</pre>
 
===Using an accumulator object===
<lang Nim>import math, strutils
 
type SDAccum = object
sdN, sdSum, sdSum2: float
 
var accum: SDAccum
 
proc add(accum: var SDAccum; value: float): float =
# Add a value to the accumulator. Return the standard deviation.
accum.sdN += 1
accum.sdSum += value
accum.sdSum2 += value * value
result = sqrt(accum.sdSum2 / accum.sdN - accum.sdSum * accum.sdSum / (accum.sdN * accum.sdN))
 
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(accum.add(value), precision = -1)</lang>
 
{{out}}
Same output.
 
===Using a closure===
<lang Nim>import math, strutils
 
func accumBuilder(): auto =
var sdSum, sdSum2, sdN = 0.0
 
result = func(value: float): float =
sdN += 1
sdSum += value
sdSum2 += value * value
result = sqrt(sdSum2 / sdN - sdSum * sdSum / (sdN * sdN))
 
let std = accumBuilder()
 
for value in [float 2, 4, 4, 4, 5, 5, 7, 9]:
echo value, " ", formatFloat(std(value), precision = -1)</lang>
 
{{out}}
Same output.
 
=={{header|Objeck}}==
Anonymous user