#!/usr/bin/perl
use warnings;
use strict;
my @c1=(1,2,3,4);
my @c2=(2,3,5,6);
my $c3=cor(\@c1,\@c2);
print "$c3\n";
sub cor {
my @x = @{$_[0]};
my @y = @{$_[1]};
my $x_mean = mean(@x);
my $y_mean = mean(@y);
my $cov_x_y = 0;
my $cov_x = 0;
my $cov_y = 0;
foreach (0..$#x) {
$cov_x_y += (($x[$_]-$x_mean)*($y[$_]-$y_mean));
$cov_x += (($x[$_]-$x_mean)*($x[$_]-$x_mean));
$cov_y += (($y[$_]-$y_mean)*($y[$_]-$y_mean));
}
return $cov_x_y/(sqrt($cov_x)*sqrt($cov_y));
}
sub mean {
my @a = @_;
my $sum = 0;
foreach (@a) {
$sum += $_;
}
return $sum/($#a+1);
}
网友评论