## 2017年4月19日水曜日

### Python - 数学 - ベクトル - 上三角線形方程式を解く - 後退代入

コード(Emacs)

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

import unittest

from vec import Vec

def zero_vector(D):
labels = D
function = {k: 0 for k in labels}
return Vec(labels, function)

def list2vec(l):
return Vec(set(range(len(l))), {i: v for i, v in enumerate(l)})

def triangular_solve_n(rowlist, b):
D = rowlist[0].D
n = len(D)
assert D == set(range(n))
x = zero_vector(D)
for i in reversed(range(n)):
x[i] = (b[i] - rowlist[i] * x) / rowlist[i][i]
return x

class Test(unittest.TestCase):

def setUp(self):
pass

def tearDown(self):
pass

def test_triangular_solve_n(self):
rowlist = list(
map(list2vec,
[[1, 0.5, -2, 4],
[0, 3, 3, 2],
[0, 0, 1, 5],
[0, 0, 0, 2]
])
)
b = [-8, 3, -4, 6]
x = triangular_solve_n(rowlist, b)
self.assertEqual(
x, Vec({0, 1, 2, 3}, {0: -67, 1: 18, 2: -19, 3: 3}))

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

```\$ ./sample11_4.py -v
test_triangular_solve_n (__main__.Test) ... ok

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

OK
\$
```