開発環境
- macOS High Sierra - Apple
- Emacs (Text Editor)
- Python 3.6 (プログラミング言語)
Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の4章(SymPyで代数と式を計算する)、4.6(プログラミングチャレンジ)、問題4-3(級数の和)を取り組んでみる。
コード(Emacs)
Python 3
#!/usr/bin/env python3 from sympy import pprint, symbols, sympify, SympifyError, summation if __name__ == '__main__': n = symbols('n') while True: term = input('Enter the nth term: ') if term == 'q': break try: term = sympify(term) except SympifyError as err: print(type(err), err) else: try: nums = input('Enter the number of terms: ') nums = int(nums) except Exception as err: print(type(err), err) else: s = summation(term, (n, 1, nums)) pprint(s)
入出力結果(Terminal, Jupyter(IPython))
$ ./sample3.py Enter the nth term: a + (n - 1) * d Enter the number of terms: 3 3⋅a + 3⋅d Enter the nth term: a + (n - 1) * d Enter the number of terms: 4 4⋅a + 6⋅d Enter the nth term: 2a <class 'sympy.core.sympify.SympifyError'> Sympify of expression 'could not parse '2a'' failed, because of exception being raised: SyntaxError: invalid syntax (<string>, line 1) Enter the nth term: a + (n - 1) * d Enter the number of terms: c <class 'ValueError'> invalid literal for int() with base 10: 'c' Enter the nth term: x ** n / n Enter the number of terms: 5 5 4 3 2 x x x x ── + ── + ── + ── + x 5 4 3 2 Enter the nth term: x ** n / n Enter the number of terms: 6 6 5 4 3 2 x x x x x ── + ── + ── + ── + ── + x 6 5 4 3 2 Enter the nth term: q $
0 コメント:
コメントを投稿