File Coverage

blib/lib/Math/EWMA.pm
Criterion Covered Total %
statement 19 19 100.0
branch 6 6 100.0
condition n/a
subroutine 4 4 100.0
pod 1 1 100.0
total 30 30 100.0


line stmt bran cond sub pod time code
1             package Math::EWMA;
2 2     2   40223 use Moo;
  2         26204  
  2         11  
3 2     2   3723 use namespace::autoclean;
  2         26978  
  2         21  
4 2     2   163 use Scalar::Util qw(looks_like_number);
  2         3  
  2         880  
5              
6             our $VERSION = '0.02';
7             $VERSION = eval $VERSION;
8              
9              
10             has alpha => (
11             is =>'ro',
12             isa => sub { die "$_[0] is not a number!" unless looks_like_number $_[0]},
13             required => '1',
14             );
15              
16             has last_avg => (
17             is =>'ro',
18             isa => sub { die "$_[0] is not a number!" unless looks_like_number $_[0]},
19             writer => '_set_last_avg',
20             );
21              
22             has precision => (
23             is => 'rw',
24             isa => sub { die "$_[0] is not a number!" unless looks_like_number $_[0]},
25             default => 2,
26             );
27              
28              
29             sub ewma
30             {
31 10     10 1 2056 my ($self, $current) = @_;
32 10         23 my $last = $self->last_avg();
33 10         17 my $alpha = $self->alpha();
34 10         200 my $prec = $self->precision();
35              
36 10 100       509 return sprintf("%.${prec}f",$last) unless defined $current;
37 6 100       28 die "ewma() works on numbers only!" unless looks_like_number $current;
38              
39 5 100       8 $last = $current if not defined $last;
40 5         14 my $ewma = (1 - $alpha) * $last + $alpha * $current;
41 5         66 $self->_set_last_avg($ewma);
42 5         91 return sprintf("%.${prec}f",$ewma);
43             }
44              
45              
46             __PACKAGE__->meta->make_immutable;
47             1;
48              
49             __END__