開発環境
- OS X El Capitan - Apple (OS)
- Emacs (Text Editor)
- Python 3.5 (プログラミング言語)
Doing Math with Python: Use Programming to Explore Algebra, Statistics, Calculus, and More! (Amit Saha (著)、No Starch Press)のChapter 4.(Algebra and Symbolic Math with SymPy)、Programming Challenges #4: Solving Single-Variable Inequalities(No. 2939)を解いてみる。
#4: Solving Single-Variable Inequalities(No. 2939)
コード(Emacs)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sympy
def isolve(ineq_obj):
x = sympy.Symbol('x')
lhs = ineq_obj.lhs
rel = ineq_obj.rel_op
if lhs.is_polynomial():
p = sympy.Poly(lhs, x)
rel = ineq_obj.rel_op
return sympy.solve_poly_inequality(p, rel)
if lhs.is_rational_function():
numer, denom = lhs.as_numer_denom()
p1 = sympy.Poly(numer)
p2 = sympy.Poly(denom)
return sympy.solve_rational_inequalities([[((p1, p2), rel)]])
return sympy.solve_univariate_inequality(ineq_obj, x, relational=False)
if __name__ == '__main__':
while True:
expr = input('Enter the inequality expression: ')
if expr == 'q':
break
try:
ineq_obj = sympy.sympify(expr)
except sympy.SympifyError as err:
print(err)
else:
print(isolve(ineq_obj))
入出力結果(Terminal, IPython)
$ ./sample4.py Enter the inequality expression: -x**2 + 4 < 0 [(-oo, -2), (2, oo)] Enter the inequality expression: ((x-1)/(x+2)) > 0 (-oo, -2) U (1, oo) Enter the inequality expression: sin(x) - 0.6 > 0 (0.643501108793284, 2.49809154479651) Enter the inequality expression: q $
0 コメント:
コメントを投稿