2019年3月16日土曜日

開発環境

Math Adventures with Python: An Illustrated Guide to Exploring Math with Code (Peter Farrell(著)、No Starch Press)のPART 2(RIDING INTO MATH TERRITORY)、8(USING MATRICES FOR COMPUTER GRAPHICS AND SYSTEMS OF EQUATIONS)、EXERCISE 8-2(ENTER THE MATRIX)の解答を求めてみる。

コード

Python 3

sample2_test.py

import unittest
from sample2 import gauss


class TestGauss(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        pass

    def test_B(self):
        B = [[2, 1, -1, 8],
             [-3, -1, 2, -1],
             [-2, 1, 2, -3]]
        expected = [[1.0, 0.0, 00, 32.0],
                    [0.0, 1.0, 0.0, -17.0],
                    [-0.0, -0.0, 1.0, 39.0]]
        actual = gauss(B)
        self.assertEqual(expected, actual)


if __name__ == '__main__':
    unittest.main()

sample2.py

#!/usr/bin/env python3
def gauss(A):
    for j, row in enumerate(A):
        if row[j] != 0:
            divisor = row[j]
            for i, term in enumerate(row):
                row[i] = term / divisor
        for i, row_i in enumerate(A):
            if i != j:
                add_inverse = -1 * row_i[j]
                for l, _ in enumerate(row_i):
                    row_i[l] += add_inverse * row[l]
    return A


if __name__ == '__main__':
    import pprint
    A = [[2, -1, 5, 1, 3],
         [3, 2, 2, -6, 32],
         [1, 3, 3, -1, 47],
         [5, -2, 3, 3, -49]]
    B = gauss(A)
    pprint.pprint(B)

入出力結果(cmd(コマンドプロンプト)、Terminal、Jupyter(IPython))

C:\Users\...>py -3 sample2_test.py -v
test_B (__main__.TestGauss) ... ok

----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

C:\Users\...>py -3 sample2.py
[[1.0, 0.0, 0.0, 0.0, -7.333333333333336],
 [0.0, 1.0, 0.0, 0.0, 10.666666666666666],
 [0.0, 0.0, 1.0, 0.0, 6.333333333333334],
 [0.0, 0.0, 0.0, 1.0, -3.3333333333333344]]
 
C:\Users\...>

0 コメント:

コメントを投稿