## 2020年3月10日火曜日

### 数学 - Python - 代数学 - 1次方程式, 2次方程式 - 因数分解、2次方程式の解

1. $\begin{array}{l}a\left(a-1\right){x}^{2}-\left(2{a}^{2}-1\right)x+a\left(a+1\right)=0\\ \left(ax-\left(a+1\right)\right)\left(\left(a-1\right)x-a\right)=0\\ x=\frac{a+1}{a},\frac{a}{a-1}\end{array}$

2. $\begin{array}{l}\left(x-a\right)\left(2ax+{a}^{2}+1\right)=0\\ x=a,-\frac{{a}^{2}+1}{2a}\end{array}$

3. $\begin{array}{l}\left(ax-1\right)\left(bx-1\right)=0\\ x=\frac{1}{a},\frac{1}{b}\end{array}$

4. $\begin{array}{l}\left(\left(a-b\right)x-\left(c-a\right)\right)\left(x-1\right)=0\\ x=1,\frac{c-a}{a-b}\end{array}$

コード

#!/usr/bin/env python3
from unittest import TestCase, main
from sympy import symbols, solveset, plot

print('2.')

a, b, c, x = symbols('a, b, c, x')
abcs = [(a * (a - 1), -(2 * a ** 2 - 1), a * (a + 1)),
(2 * a, 1 - a ** 2, -a * (a ** 2 + 1)),
(a * b, -(a + b), 1),
(a - b, b - c, c - a)]
fs = [c1 * x ** 2 + c2 * x + c3 for c1, c2, c3 in abcs]

class MyTestCase(TestCase):
def test(self):
xss = [{(a + 1) / a, a / (a - 1)},
{a, -(a ** 2 + 1) / (2 * a)},
{1 / a, 1 / b},
{1 + 0 * a, (c - a) / (a - b)}]
for i, (f, xs) in enumerate(zip(fs, xss), 1):
print(f'({i})')
self.assertEqual({x0.simplify()for x0 in solveset(f, x)},
{x0.simplify() for x0 in xs})

p = plot(*[f.subs({a: 2, b: -1, c: 3}) for f in fs],
(x, -5, 5),
ylim=(-5, 5),
legend=True,
show=False)

colors = ['red', 'green', 'blue', 'brown', 'orange',
'purple', 'pink', 'gray', 'skyblue', 'yellow']

for o, color in zip(p, colors):
o.line_color = color

p.show()
p.save(f'sample2.png')

if __name__ == "__main__":
main()

% ./sample2.py
2.
(1)
(2)
(3)
(4)
.
----------------------------------------------------------------------
Ran 1 test in 0.790s

OK
%