Cumulative standard deviation: Difference between revisions
→{{header|Perl}}: shorter version with closure
m (→{{header|Perl 6}}: one newline missing) |
(→{{header|Perl}}: shorter version with closure) |
||
Line 1,299:
}
print "std dev = $sd\n";</lang>
A much shorter version using a closure and a property of the variance:
<lang perl># <(x - <x>)²> = <x²> - <x>²
sub stddev;
{
my @sum;
sub stddev {
my $x = shift;
$sum[0]++;
return sqrt(
($sum[2] += $x**2) / $sum[0] -
(($sum[1] += $x) / $sum[0])**2
);
}
}
use feature qw(say);
say stddev $_ for 2, 4, 4, 4, 5, 5, 7, 9;</lang>
{{out}}
<pre>0
1
0.942809041582063
0.866025403784439
0.979795897113272
1
1.39970842444753
2</pre>
=={{header|Perl 6}}==
|