2015年12月24日木曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 1.(Visualizing Data with Graphs)、Programming Challenges #1: Better Correlation Coefficient-Finding Program(No. 2269)を解いてみる。

#1: Better Correlation Coefficient-Finding Program(No. 2269)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import random

def find_corr_x_y(x, y):
    n = len(x)
    if n != len(y):
        raise Exception("correlation can't be found.")
    prod = []
    for xi, yi in zip(x, y):
        prod.append(xi * yi)

    sum_prod_x_y = sum(prod)
    sum_x = sum(x)
    sum_y = sum(y)
    squared_sum_x = sum_x ** 2
    squared_sum_y = sum_y ** 2
    x_square = []
    for xi in x:
        x_square.append(xi ** 2)
    x_square_sum = sum(x_square)

    y_square = []
    for yi in y:
        y_square.append(yi ** 2)
    y_square_sum = sum(y_square)
    numerator = n * sum_prod_x_y - sum_x * sum_y
    denominator_term1 = n * x_square_sum - squared_sum_x
    denominator_term2 = n * y_square_sum - squared_sum_y
    denominator = (denominator_term1 * denominator_term2) ** (1/2)
    correlation = numerator / denominator
    return correlation
    


if __name__ == '__main__':
    x = [random.randrange(100) for _ in range(10)]
    y = [random.randrange(100) for _ in range(10)]
    for x, y in [(x, y), (x, y + [0]), (x + [0], y), (x + [0], [0] + y)]:
        print(x, y, sep='\n')
        try:
            print(find_corr_x_y(x, y))
        except Exception as err:
            print(err)

入出力結果(Terminal, IPython)

$ ./sample1.py
[43, 11, 72, 80, 66, 51, 68, 67, 1, 43]
[27, 88, 35, 45, 22, 29, 32, 40, 13, 2]
-0.10647324656200796
[43, 11, 72, 80, 66, 51, 68, 67, 1, 43]
[27, 88, 35, 45, 22, 29, 32, 40, 13, 2, 0]
correlation can't be found.
[43, 11, 72, 80, 66, 51, 68, 67, 1, 43, 0]
[27, 88, 35, 45, 22, 29, 32, 40, 13, 2]
correlation can't be found.
[43, 11, 72, 80, 66, 51, 68, 67, 1, 43, 0]
[0, 27, 88, 35, 45, 22, 29, 32, 40, 13, 2]
0.43310573221520043
$

0 コメント:

コメントを投稿