Cumulative standard deviation: Difference between revisions

(→‎{{header|Perl 6}}: added PHP header)
Line 2,206:
2</pre>
=={{header|PHP}}==
This is just straight PHP class usage:
<lang PHP><?php
class sdcalc {
private $cnt, $sumup, $square;
 
function __construct() {
$this->reset();
}
# callable on an instance
function reset() {
$this->cnt=0; $this->sumup=0; $this->square=0;
}
function add($f) {
$this->cnt++;
$this->sumup += $f;
$this->square += pow($f, 2);
return $this->calc();
}
function calc() {
if ($this->cnt==0 || $this->sumup==0) {
return 0;
} else {
return sqrt($this->square / $this->cnt - pow(($this->sumup / $this->cnt),2));
}
}
}
 
# start test, adding test data one by one
$c = new sdcalc();
foreach ([2,4,4,4,5,5,7,9] as $v) {
printf('Adding %g: result %g%s', $v, $c->add($v), PHP_EOL);
}</lang>
 
This will produce the output:
 
<pre>Adding 2: result 0
Adding 4: result 1
Adding 4: result 0.942809
Adding 4: result 0.866025
Adding 5: result 0.979796
Adding 5: result 1
Adding 7: result 1.39971
Adding 9: result 2
</pre>
 
=={{header|PL/I}}==
Anonymous user