## 2020年5月14日木曜日

### 数学 - Pytyhon - 解析学 - 多変数の関数 - 合成微分律と勾配ベクトル - 方向微分係数 - 対数関数、累乗(平方)、累乗根(平方根)、最大値、内積、三角関数(余弦)

1. $\begin{array}{l}gradf\left(x,y\right)\\ =grad\mathrm{log}{\left({x}^{2}+{y}^{2}\right)}^{\frac{1}{2}}\\ =\left({\left({x}^{2}+{y}^{2}\right)}^{-\frac{1}{2}}\frac{1}{2}{\left({x}^{2}+{y}^{2}\right)}^{-\frac{1}{2}}2x,{\left({x}^{2}+{y}^{2}\right)}^{-\frac{1}{2}}\frac{1}{2}{\left({x}^{2}+{y}^{2}\right)}^{-\frac{1}{2}}2y\right)\\ =\left(\frac{x}{{x}^{2}+{y}^{2}},\frac{y}{{x}^{2}+{y}^{2}}\right)\\ gradf\left(1,1\right)=\frac{1}{2}\left(1,1\right)\\ \frac{1}{2}\left(1,1\right)·\frac{\left(2,1\right)}{\sqrt{4+1}}\\ =\frac{2+1}{2\sqrt{5}}\\ =\frac{3}{2\sqrt{5}}\end{array}$

2. $\begin{array}{l}grad\left(xy+yz+zx\right)\\ =\left(y+z,x+z,y+x\right)\\ gradf\left(-1,1,7\right)\\ =\left(8,6,0\right)\\ =2\left(4,3,0\right)\\ 2\left(4,3,0\right)·\frac{\left(3,4,-12\right)}{\sqrt{9+16+144}}\\ =\frac{2}{13}\left(12+12\right)\\ =\frac{48}{13}\end{array}$

3. $\begin{array}{l}grad\left(4{x}^{2}+9{y}^{2}\right)\\ =\left(8x,18y\right)\\ =2\left(4x,9y\right)\\ gradf\left(2,1\right)=2\left(8,9\right)\\ ∥gradf\left(2,1\right)∥\\ =2\sqrt{64+81}\\ =2\sqrt{145}\end{array}$

コード

#!/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')

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()


% ./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
%