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   47702 use Moo;
  2         28214  
  2         13  
3 2     2   5600 use namespace::autoclean;
  2         25364  
  2         20  
4 2     2   170 use Scalar::Util qw(looks_like_number);
  2         4  
  2         927  
5              
6             our $VERSION = '0.03';
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 2839 my ($self, $current) = @_;
32 10         29 my $last = $self->last_avg();
33 10         20 my $alpha = $self->alpha();
34 10         231 my $prec = $self->precision();
35              
36 10 100       635 return sprintf("%.${prec}f",$last) unless defined $current;
37 6 100       34 die "ewma() works on numbers only!" unless looks_like_number $current;
38              
39 5 100       10 $last = $current if not defined $last;
40 5         15 my $ewma = (1 - $alpha) * $last + $alpha * $current;
41 5         138 $self->_set_last_avg($ewma);
42 5         95 return sprintf("%.${prec}f",$ewma);
43             }
44              
45              
46             __PACKAGE__->meta->make_immutable;
47             1;
48              
49             __END__