Python 获取用户给定的函数

Obtaining a function given by the user in Python

我在使用 parse_expr sympy 函数读取函数时遇到问题。 以下是我的使用方法:

from sympy import*
import sympy as smp
import numpy as np
from sympy.parsing.sympy_parser import parse_expr
print("Welcome...")
x=smp.Symbol('x')
function=input("Enter your function in terms of X\nIf you want to use Fixed point method input de G(x) expresion\n")
function=parse_expr(function, x)

这就是我得到的:

Welcome...
Enter your function in terms of X
If you want to use Fixed point method input de G(x) expresion
2*x

Traceback (most recent call last):
  File "c:\Users\jp159\Desktop\Desktop\Studies\Exercises.py", line 8, in <module>
    function=parse_expr(function, x)
  File "C:\Users\jp159\AppData\Local\Programs\Python\Python39\lib\site-packages\sympy\parsing\sympy_parser.py", line 988, in parse_expr
    raise TypeError('expecting local_dict to be a dict')
TypeError: expecting local_dict to be a dict

在初始化为:

的 isympy 会话中
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()

Documentation can be found at https://docs.sympy.org/1.8/

因为 local_dict 是可选的,所以我们省略它:

In [1]: parse_expr('2*x')
Out[1]: 2⋅x

但我们可以创建一个字典 - 引用定义的符号之一:

In [4]: parse_expr('2*x',{'x':x})
Out[4]: 2⋅x

In [5]: parse_expr('2*x',{'x':y})
Out[5]: 2⋅y

我也可以使用看起来不像任何已定义符号的字符串:

In [7]: parse_expr('2*X')
Out[7]: 2⋅X

In [8]: _.free_symbols
Out[8]: {X}

新程序员的一项关键技能是阅读文档。是的,这通常很难理解,但它仍然应该是第一站。 SO(和一般网络搜索)应该稍后出现。

sympy 是用 Python 编写的,因此假定具有该语言的基本知识。