2020年4月25日土曜日

学習環境

解析入門 原書第3版 (S.ラング(著)、松坂 和夫(翻訳)、片山 孝次(翻訳)、岩波書店)の第Ⅵ部(多変数の関数)、第20章(合成微分律と勾配ベクトル)、1(合成微分律)の練習問題9の解答を求めてみる。



    1. X = x 1 , , x n

      とおく。

      このとき、

      r = X = k = 1 n x k 2

      求める勾配ベクトルは

      g r a d f X = D 1 f X , , D n . f X D k f X = d dx k f X = d dx k g r = d dx k · 1 r = - 1 r 2 · x k k = 1 n x k 2 = - x k r 3 g r a d f X = - X r 3

    2. g r a d f X = g r a d g r = g r a d r 2 = 2 r x 1 r , , 2 r x n r = 2 X

    3. d dx k 1 r 3 = - 3 r 2 r 6 - x k r = - 3 x k r 5 g r a d f X = - 3 X r 5

    4. d dx k e - r 2 = - 2 r e - r 2 · x k r = - 2 e - r 2 x k g r a d f X = - 2 e - r 2 X

    5. d dx k log 1 r = - r · 1 r 2 x k r = - x k r 2 g r a d f X = - X r 2

    6. d dx k 4 r m = - 4 · m r m - 1 r 2 m · x k r = - 4 m x k r m + 2 g r a d f X = - 4 m X r m + 2

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from sympy import symbols, Function, Matrix, exp, log

print('9.')

xs = symbols('x:5', real=True)
X = Matrix(xs)
r = X.norm()
m = symbols('m', integer=True)
fs = [1 / r, r ** 2, 1 / r ** 3, exp(-r ** 2), log(1 / r), 4 / r ** m]
gradfs = [Matrix([f.diff(x, 1) for x in xs])
          for f in fs]


class TestDerivativeChainRule(TestCase):
    def test_a(self):
        self.assertEqual(gradfs[0], - X / r ** 3)

    def test_b(self):
        self.assertEqual(gradfs[1], 2 * X)

    def test_c(self):
        self.assertEqual(gradfs[2], -3 * X / r ** 5)

    def test_d(self):
        self.assertEqual(gradfs[3], -2 * exp(-r ** 2) * X)

    def test_e(self):
        self.assertEqual(gradfs[4], -X / r ** 2)

    def test_f(self):
        for m0 in range(-10, 11):
            if m == 1:
                continue
            self.assertEqual(gradfs[5].subs({m: m0}),
                             -4 * m0 * X/r ** (m0 + 2))


if __name__ == "__main__":
    main()

入出力結果(Zsh、PowerShell、Terminal、Jupyter(IPython))

% ./sample9.py -v
9.
test_a (__main__.TestDerivativeChainRule) ... ok
test_b (__main__.TestDerivativeChainRule) ... ok
test_c (__main__.TestDerivativeChainRule) ... ok
test_d (__main__.TestDerivativeChainRule) ... ok
test_e (__main__.TestDerivativeChainRule) ... ok
test_f (__main__.TestDerivativeChainRule) ... ok

----------------------------------------------------------------------
Ran 6 tests in 0.087s

OK
%

0 コメント:

コメントを投稿