use Math::Cephes qw(gamma igamc); # カイ二乗分布 Chi-Squared Distribution # 引数 変数 自由度 ($X, $DegreesOfFreedom) # 戻り値 カイ二乗分布 (@ChiSquaredDistribution) sub CHISQUAREDDISTRIBUTION{ my ($X, $DegreesOfFreedom) = @_; my @ChiSquaredDistribution = (); my $IncompleteGammaFunction = 0; # 変数,自由度の確認 if(($X < 0) || ($DegreesOfFreedom <= 0)){ return 0; } # 確率密度関数 Frequency Function $ChiSquaredDistribution[0] = &FREQUENCYFUNCTION($X, $DegreesOfFreedom); # 累積分布関数 不完全ガンマ関数 Incomplete Gamma Function $IncompleteGammaFunction = igamc(($DegreesOfFreedom / 2), ($X / 2)); # 下側累積確率 Lower Cumulative Distribution $ChiSquaredDistribution[1] = 1 - $IncompleteGammaFunction; # 上側累積確率 Upper Cumulative Distribution $ChiSquaredDistribution[2] = $IncompleteGammaFunction; return @ChiSquaredDistribution; } # 確率密度関数 Frequency Function # 引数 変数 自由度 ($X, $DegreesOfFreedom) # 戻り値 確率密度関数 ($FrequencyFunction) sub FREQUENCYFUNCTION{ my ($X, $DegreesOfFreedom) = @_; my $FrequencyFunction = 0; my $Pi = atan2(1, 1) * 4; my $Num = 0; my $Den = 0; if($X == 0){ return 0; } # 分子 $Num = ($X ** (($DegreesOfFreedom / 2) - 1)) * exp(-($X / 2)); # 分母 $Den = (2 ** ($DegreesOfFreedom / 2)) * gamma($DegreesOfFreedom / 2); # カイ二乗分布 Frequency Function $FrequencyFunction = $Num / $Den; return $FrequencyFunction; }