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   61549 use Moo;
  2         31153  
  2         14  
3 2     2   4579 use namespace::autoclean;
  2         38588  
  2         20  
4 2     2   149 use Scalar::Util qw(looks_like_number);
  2         4  
  2         796  
5              
6             our $VERSION = '0.01';
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 1680 my ($self, $current) = @_;
32 10         27 my $last = $self->last_avg();
33 10         16 my $alpha = $self->alpha();
34 10         200 my $prec = $self->precision();
35              
36 10 100       603 return sprintf("%.${prec}f",$last) unless defined $current;
37 6 100       26 die "ewma() works on numbers only!" unless looks_like_number $current;
38              
39 5 100       9 $last = $current if not defined $last;
40 5         11 my $ewma = (1 - $alpha) * $last + $alpha * $current;
41 5         64 $self->_set_last_avg($ewma);
42 5         82 return sprintf("%.${prec}f",$ewma);
43             }
44              
45              
46             __PACKAGE__->meta->make_immutable;
47             1;
48              
49             __END__