美文网首页
利用perl计算person相关系数

利用perl计算person相关系数

作者: qujingtao | 来源:发表于2021-07-17 10:48 被阅读0次
    #!/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);
    }
    

    相关文章

      网友评论

          本文标题:利用perl计算person相关系数

          本文链接:https://www.haomeiwen.com/subject/nefwpltx.html