``````package Statistics::Welford;

=pod

Statistics::Welford - Standard statistics using Welford's algorithm

my \$stat = Statistics::Welford->new;

while (1) {
...
}

print \$stat->mean;

Standard statistics using Welford's algorithm

=cut

use strict;
use warnings;

our \$VERSION = '0.02';

=pod

my \$stat = Statistics::Welford->new;

The C<new> constructor lets you create a new B<Statistics::Welford> object.

=cut

sub new {
my \$class = shift;
my \$self  = bless { @_ }, \$class;
\$self->{n} = 0;
return \$self;
}

=pod

Add an entry to the statistics base

=cut

my (\$self, \$x) = @_;

\$self->{n}++;
if (\$self->{n} == 1) {
\$self->{old_m} = \$x;
\$self->{new_m} = \$x;
\$self->{min} = \$x;
\$self->{max} = \$x;
\$self->{old_s} = 0.0;
return \$self;
}
\$self->{new_m} = \$self->{old_m} + (\$x - \$self->{old_m})/\$self->{n};
\$self->{new_s} = \$self->{old_s} + (\$x - \$self->{old_m})*(\$x - \$self->{new_m});
\$self->{min} = \$x if \$x < \$self->{min};
\$self->{max} = \$x if \$x > \$self->{max};

# set up for next iteration
\$self->{old_m} = \$self->{new_m};
\$self->{old_s} = \$self->{new_s};
return \$self;
}

Returns the number of entries to the statistics base

=cut

sub n {
my \$self = shift;
return \$self->{n};
}

Returns the minimum number in the statistics base

=cut

sub min {
my \$self = shift;
return \$self->{min};
}

Returns the maximum number in the statistics base

=cut

sub max {
my \$self = shift;
return \$self->{max};
}

Returns the mean value

=cut

sub mean {
my \$self = shift;
return \$self->{n} > 0 ? \$self->{new_m} : 0.0;
}

Returns the variance value

=cut

sub variance {
my \$self = shift;
return \$self->{n} > 1 ? \$self->{new_s}/(\$self->{n} - 1) : 0.0;
}

Returns the standard deviation value

=cut

sub standard_deviation {
my \$self = shift;
return sqrt( \$self->variance );
}

1;

=pod