2020年5月14日木曜日

学習環境

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



    1. gradfx,y=gradlogx2+y212=x2+y2-1212x2+y2-122x,x2+y2-1212x2+y2-122y=xx2+y2,yx2+y2gradf1,1=121,1121,1·2,14+1=2+125=325

    2. gradxy+yz+zx=y+z,x+z,y+xgradf-1,1,7=8,6,0=24,3,024,3,0·3,4,-129+16+144=21312+12=4813

    3. grad4x2+9y2=8x,18y=24x,9ygradf2,1=28,9gradf2,1=264+81=2145

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from sympy import symbols, Matrix, log, Rational, sqrt
from sympy.plotting import plot3d

print('2.')

x, y, z = symbols('x, y, z')


def grad(f, p):
    return Matrix([f.diff(o, 1) for o in [x, y, z]]).subs(p)


fs = [log((x ** 2+y ** 2) ** Rational(1, 2)),
      4 * x ** 2 + 9 * y ** 2]


class TestDirectionalDerivative(TestCase):
    def test_a(self):
        a = Matrix([2, 1, 0])
        self.assertEqual(
            grad(fs[0], {x: 1, y: 1}).dot(a / a.norm()),
            3 / (2 * sqrt(5)))

    def test_b(self):
        a = Matrix([3, 4, -12])
        self.assertEqual(
            grad(x * y + y * z + z * x, {x: -1, y: 1, z: 7}).dot(a / a.norm()),
            Rational(48, 13))

    def test_c(self):
        self.assertEqual(grad(fs[1], {x: 2, y: 1}).norm(), 2 * sqrt(145))


for i, f in zip(['a', 'c'], fs):
    p = plot3d(f,
               (x, -5, 5),
               (y, -5, 5),
               show=False)
    p.save(f'sample2_{i}.png')
p.show()


if __name__ == "__main__":
    main()

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

% ./sample2.py -v
2.
test_a (__main__.TestDirectionalDerivative) ... ok
test_b (__main__.TestDirectionalDerivative) ... ok
test_c (__main__.TestDirectionalDerivative) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.023s

OK
%

0 コメント:

コメントを投稿