## 2020年2月6日木曜日

### 数学 - Python - 図形と代数の交錯する世界 - 平面上のベクトル - ベクトルとその演算 - 内積を成分で表すこと - 内積、長さ、余弦

1. $\begin{array}{l}\mathrm{cos}\theta \\ =\frac{a·b}{\left|a\right|\left|b\right|}\\ =\frac{\left(2,3\right)·\left(1,-1\right)}{\sqrt{\left(2,3\right)}\sqrt{\left(1,-1\right)}}\\ =\frac{2-3}{\sqrt{4+9}\sqrt{1+1}}\\ =\frac{-1}{\sqrt{13}\sqrt{2}}\\ =-\frac{1}{\sqrt{26}}\end{array}$

2. $\begin{array}{l}\mathrm{cos}\theta \\ =\frac{3}{3·2}\\ =\frac{1}{2}\\ \theta =\frac{\pi }{3}\end{array}$

3. $\begin{array}{l}\mathrm{cos}\theta \\ =\frac{1}{\sqrt{2}}\\ \theta =\frac{\pi }{4}\end{array}$

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from sympy import symbols, Matrix, sqrt, cos, Rational, pi, solveset, Interval
from sympy import FiniteSet

print('16.')

theta = symbols('θ')
domain = Interval(0, pi)

def cosine(a, b):
return a.dot(b) / (a.norm() * b.norm())

class MyTestCase(TestCase):
def test1(self):
a = Matrix([2, 3])
b = Matrix([1, -1])
self.assertEqual(cosine(a, b), -1 / sqrt(26))

def test2(self):
a = Matrix([-3, 0])
b = Matrix([-1, sqrt(3)])
c = cosine(a, b)
self.assertEqual(c, Rational(1, 2))
self.assertEqual(
solveset(c - cos(theta), domain=domain), FiniteSet(pi / 3))

def test3(self):
self.assertEqual(
solveset(cos(theta) - 1 / sqrt(2), domain=domain), FiniteSet(pi / 4))

if __name__ == "__main__":
main()


% ./sample16.py -v
16.
test1 (__main__.MyTestCase) ... ok
test2 (__main__.MyTestCase) ... ok
test3 (__main__.MyTestCase) ... ok

----------------------------------------------------------------------
Ran 3 tests in 0.602s

OK
%