Averages/Simple moving average: Difference between revisions
no edit summary
No edit summary |
|||
Line 4,800:
2 3 3.8
1 2 3
</pre>
=={{header|Vlang}}==
{{trans|Go}}
<lang vlang>fn sma(period int) fn(f64) f64 {
mut i := int(0)
mut sum := f64(0)
mut storage := []f64{len: 0, cap:period}
return fn[mut storage, mut sum, mut i, period](input f64) f64 {
if storage.len < period {
sum += input
storage << input
}
sum += input - storage[i]
storage[i], i = input, (i+1)%period
return sum / f64(storage.len)
}
}
fn main() {
sma3 := sma(3)
sma5 := sma(5)
println("x sma3 sma5")
for x in [f64(1), 2, 3, 4, 5, 5, 4, 3, 2, 1] {
println("${x:5.3f} ${sma3(x):5.3f} ${sma5(x):5.3f}")
}
}</lang>
{{out}}
<pre>
x sma3 sma5
1.000 1.000 1.000
2.000 1.500 1.500
3.000 2.000 2.000
4.000 3.000 2.500
5.000 4.000 3.000
5.000 4.667 3.800
4.000 4.667 4.200
3.000 4.000 4.200
2.000 3.000 3.800
1.000 2.000 3.000
</pre>
|