2016年1月24日日曜日

開発環境

  • 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 #2: Graphical Equation Solver(No. 2907)を解いてみる。

#2: Graphical Equation Solver(No. 2907)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sympy
import sympy.plotting as symplt

def plot_expression(*exprs):
    y = sympy.Symbol('y')
    exprs_y = map(lambda expr: sympy.solve(expr, y)[0], exprs)
    symplt.plot(*exprs_y, legend=True)
    
expr1 = input('Enter your first expression in terms of x and y: ')
expr2 = input('Enter your second expression in terms of x and y: ')

try:
    expr1 = sympy.sympify(expr1)
    expr2 = sympy.sympify(expr2)    
except sympy.SympifyError as err:
    print(err)
else:
    plot_expression(expr1, expr2)
    print(sympy.solve((expr1, expr2), dict=True))

入出力結果(Terminal, IPython)

$ ./sample2.py
Enter your first expression in terms of x and y: 2*x+3*y-6
Enter your second expression in terms of x and y: 3*x+2*y-12
[{y: -6/5, x: 24/5}]
$

0 コメント:

コメントを投稿

Comments on Google+: