2018年6月30日土曜日

開発環境

Pythonからはじめる数学入門 (Amit Saha (著)、黒川 利明 (翻訳)、オライリージャパン)の7章(初等解析問題を解く)、7.10(プログラミングチャレンジ)、問題7-1(ある点での関数の連続性を検証する)を取り組んでみる。

コード(Emacs)

Python 3

#!/usr/bin/env python3
from sympy import pprint, symbols, sympify, SympifyError, Limit


def is_continuous(f, v, p):
    try:
        f = sympify(f)
    except SympifyError as err:
        print(err)
        return
    v = symbols(v)
    try:
        p = float(p)
    except Exception as err:
        print(type(err), err)
        return
    l = Limit(f, v, p, dir='-').doit()
    r = Limit(f, v, p, dir='+').doit()
    return l == r


if __name__ == '__main__':
    while True:
        f = input('Enter a function in one variable: ')
        if f == 'q':
            break
        v = input('Enter the variable: ')
        p = input('Enter the point to check the continuity at: ')
        b = is_continuous(f, v, p)
        if not b is None:
            if b:
                print(f'{f} is continuous at {p}')
            else:
                print(f'{f} is not continuous at {p}')

入出力結果(Terminal, Jupyter(IPython))

$ ./sample1.py
Enter a function in one variable: x *
Enter the variable: x
Enter the point to check the continuity at: 0
Sympify of expression 'could not parse 'x *'' failed, because of exception being raised:
SyntaxError: unexpected EOF while parsing (<string>, line 1)
Enter a function in one variable: 1/x
Enter the variable: x
Enter the point to check the continuity at: 1
1/x is continuous at 1
Enter a function in one variable: 1/x
Enter the variable: x
Enter the point to check the continuity at: 0
1/x is not continuous at 0
Enter a function in one variable: x/y
Enter the variable: y
Enter the point to check the continuity at: 1
x/y is continuous at 1
Enter a function in one variable: 1/x
Enter the variable: x
Enter the point to check the continuity at: a
<class 'ValueError'> could not convert string to float: 'a'
Enter a function in one variable: q
$

0 コメント:

コメントを投稿

関連コンテンツ