Cumulative standard deviation: Difference between revisions

Content added Content deleted
m (sntax highlighting fixup automation)
m (→‎{{header|Raku}}: notate squaring with super-script)
Line 3,623: Line 3,623:
=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)

{{works with|Rakudo Star|2010.08}}
Using a closure:
Using a closure:
<syntaxhighlight lang="raku" line>sub sd (@a) {
<syntaxhighlight lang="raku" line>sub sd (@a) {
my $mean = @a R/ [+] @a;
my $mean = @a R/ [+] @a;
sqrt @a R/ [+] map (* - $mean)**2, @a;
sqrt @a R/ [+] map (* - $mean)², @a;
}
}
Line 3,638: Line 3,638:
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</syntaxhighlight>
say f $_ for 2, 4, 4, 4, 5, 5, 7, 9;</syntaxhighlight>


Using a state variable:
Using a state variable (remember that <tt><(x-<x>)²> = <x²> - <x>²</tt>):
<syntaxhighlight lang="raku" line># remember that <(x-<x>)²> = <x²> - <x>²
<syntaxhighlight lang="raku" line>sub stddev($x) {
sub stddev($x) {
sqrt
sqrt
(.[2] += $x**2) / ++.[0] -
( .[2] += $x²) / ++.[0]
((.[1] += $x) / .[0])**2
- ((.[1] += $x ) / .[0])²
given state @;
given state @;
}
}


say stddev $_ for <2 4 4 4 5 5 7 9>;</syntaxhighlight>
say .&stddev for <2 4 4 4 5 5 7 9>;</syntaxhighlight>


{{out}}
{{out}}