<reponame>parmalatinter/ai<gh_stars>0
#!/usr/bin/env python

# 共分散の求め方　データの散らばりの度合いを表す値
# 参考　https://blog.apar.jp/data-analysis/2822/#toc9

# 相関係数の求め方　データの散らばりの度合いを表す値
# 参考　https://blog.apar.jp/data-analysis/2822/#toc10
import math


# 平均
def Average(numList):
    return sum(numList) / len(numList)


# 偏差
def Deviation(num, average):
    val = num - average
    return val**2


# 分散
def Variance(numList):
    average = Average(numList)
    deviationList = []
    for num in numList:
        deviation = Deviation(num, average)
        deviationList.append(deviation)

    return sum(deviationList) / len(numList)


# 標準偏差
def StandardDeviation(variance):
    return math.sqrt(variance)


# 共分散
def Covariance(xNumList, yNumlist, count):
    xAverage = Average(xNumList)
    yAverage = Average(yNumlist)
    covarianceList = []

    for i in range(count):
        covariance = (xNumList[i] - xAverage) * (yNumlist[i] - yAverage)
        covarianceList.append(covariance)

    return sum(covarianceList) / count


# 相関係数
def CorrelationCoefficient(covariance, xNumList, yNumlist):
    xVariance = Variance(xNumList)
    yVariance = Variance(yNumlist)
    xStandardDeviation = StandardDeviation(xVariance)
    yStandardDeviation = StandardDeviation(yVariance)

    return covariance / (xStandardDeviation * yStandardDeviation)


def main():
    xNumList = [71, 80, 89]
    yNumlist = [80, 80, 85]
    count = 3
    covariance = Covariance(xNumList, yNumlist, count)
    print("共分散", covariance)

    correlationCoefficient = CorrelationCoefficient(covariance, xNumList,
                                                    yNumlist)
    print("相関係数", correlationCoefficient)


if __name__ == "__main__":
    main()
