学習環境
- Surface
 - Windows 10 Pro (OS)
 - Nebo(Windows アプリ)
 - iPad
 - MyScript Nebo - MyScript(iPad アプリ(iOS))
 - 参考書籍
 
解析入門 原書第3版 (S.ラング(著)、松坂 和夫(翻訳)、片山 孝次(翻訳)、岩波書店)の第Ⅵ部(多変数の関数)、第20章(合成微分律と勾配ベクトル)、3(方向微分係数)の練習問題2の解答を求めてみる。
コード
#!/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 コメント:
コメントを投稿