GenOO

 view release on metacpan or  search on metacpan

lib/GenOO/Helper/MyMath.pm  view on Meta::CPAN

# POD documentation - main docs before the code

=head1 NAME

GenOO::Helper::MyMath - A collection of useful mathematical methods

=head1 SYNOPSIS

    A collection of useful mathematical methods
    
=head1 DESCRIPTION

    This class contains useful mathematical methods such as mean, round_digits, sigmoid, min, max, glog

=head1 EXAMPLES

    #mean
    my @array = [0,20,100];
    my $mean = GenOO::Helper::MyMath->mean(\@array); #returns mean (40)

    #round_digits
    my $number = 1.012345;
    my $rounded = GenOO::Helper::MyMath->round_digits($number,2); #returns (1.01)
        
=cut

# Let the code begin...

package GenOO::Helper::MyMath;
$GenOO::Helper::MyMath::VERSION = '1.5.2';

#######################################################################
#######################   Load External modules   #####################
#######################################################################
use Modern::Perl;


#######################################################################
#######################   Interface Functions   #######################
#######################################################################
sub mean {
# Calculates the mean of the values in an array
	my ($array_ref) = @_;
	my $n=0;
	my $result=0;
	my $sum=0;

	unless (defined $array_ref) {
		warn "undefined array reference in sub mean\n";
		return undef;
	}

	foreach my $item (@$array_ref) {
		unless (defined $item) {next;}
		$sum += $item;
		$n++;
	}
	if ($n==0) {return undef;}

	$result = $sum/$n;
	return $result;
}

sub round_digits {
	my ($num,$digits) = @_;
	
	my $decimal = 10**$digits;
	my $rounded = (int($num*$decimal))/$decimal;
	return $rounded;
}

sub sigmoid {
	return 1/(1+exp(-$_[1]));
}

sub max {
# Calculates the max of the values in an array
	my ($array_ref) = @_;
	my $max_value;
	my $max_index;
	
	unless (defined $array_ref) {
		warn "undefined array reference in sub max\n";
		return (undef,undef);
	}

	for (my $i=0;$i<@{$array_ref};$i++) {
		if (defined $$array_ref[$i]) {
			if ((!defined $max_value) or ($$array_ref[$i] > $max_value)) {
				$max_value = $$array_ref[$i];
				$max_index = $i;
			}
		}
	}
	



( run in 0.608 second using v1.01-cache-2.11-cpan-75ffa21a3d4 )