## 2018年5月30日水曜日

### Python - 数学 - SymPyで代数と式を計算する - グラフを使った方程式ソルバー(sympify、symbols、solve、plotメソッド)

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の4章(SymPyで代数と式を計算する)、4.6(プログラミングチャレンジ)、問題4-2(グラフを使った方程式ソルバー)を取り組んでみる。

コード(Emacs)

Python 3

```#!/usr/bin/env python3

from sympy import pprint, symbols, sympify, SympifyError, plot, solve

x, y = symbols('x, y')
if __name__ == '__main__':
i = 0
while True:
expr1 = input('Enter your first expression in terms of x and y: ')
if expr1 == 'q':
break
expr2 = input('Enter your second expression in terms of x and y: ')
try:
expr1 = sympify(expr1)
expr2 = sympify(expr2)
except SympifyError as err:
print(type(err), err)
else:
s = solve((expr1, expr2), dict=True)
for d in s:
pprint(f'x = {d.get(x)}, y = {d.get(y)}')
ys = solve(expr1, y) + solve(expr2, y)
p = plot(*ys, legend=True, show=False)
p.save(f'sample2_{i}.svg')
i += 1
```

```\$ ./sample2.py
Enter your first expression in terms of x and y: y - x
Enter your second expression in terms of x and y: y - x - 1
Enter your first expression in terms of x and y: y - x
Enter your second expression in terms of x and y: y - 2 * x
x = 0, y = 0
Enter your first expression in terms of x and y: y - x ** 2 + 1
Enter your second expression in terms of x and y: y + x ** 2 - 2
x = -sqrt(6)/2, y = 1/2
x = sqrt(6)/2, y = 1/2
Enter your first expression in terms of x and y: y - x ** 2 - 1
Enter your second expression in terms of x and y: y + x ** 2 + 2
x = -sqrt(6)*I/2, y = -1/2
x = sqrt(6)*I/2, y = -1/2
Enter your first expression in terms of x and y: q
\$
```