[英]How to plot a math function from string?
I have a string which represents a function, like "x * (x - 32 ( 2 /x) )"
. 我有一个代表函数的字符串,例如"x * (x - 32 ( 2 /x) )"
。 I'm using matplotlib
, but I don't know how convert this string into an array of points to plot. 我正在使用matplotlib
,但是我不知道如何将该字符串转换为要绘制的点数组。
You can turn a string into code by using pythons eval
function, but this is dangerous and generally considered bad style , See this: https://stackoverflow.com/a/661128/3838691 . 您可以使用pythons eval
函数将字符串转换为代码, 但这很危险,通常被认为是不良样式 ,请参见: https : //stackoverflow.com/a/661128/3838691 。 If user can input the string, they could input something like import subprocess; subprocess.check_call(['rm', '-rf', '*'], shell=True)
如果用户可以输入字符串,则可以输入类似import subprocess; subprocess.check_call(['rm', '-rf', '*'], shell=True)
import subprocess; subprocess.check_call(['rm', '-rf', '*'], shell=True)
. import subprocess; subprocess.check_call(['rm', '-rf', '*'], shell=True)
。
So be sure that you build in reasonable security into this. 因此,请确保为此内置合理的安全性。
You can define a function that takes a string and returns a function. 您可以定义一个接受字符串并返回一个函数的函数。 We need to do a little preprocessing to allow the user to input formulas more like he is used to (^ etc.): 我们需要做一些预处理,以允许用户输入更像他习惯的公式(^等):
It seems better to define allowed and supported words than blacklisting some: 定义允许和支持的单词似乎比将某些单词列入黑名单更好:
import re
replacements = {
'sin' : 'np.sin',
'cos' : 'np.cos',
'exp': 'np.exp',
'sqrt': 'np.sqrt',
'^': '**',
}
allowed_words = [
'x',
'sin',
'cos',
'sqrt',
'exp',
]
def string2func(string):
''' evaluates the string and returns a function of x '''
# find all words and check if all are allowed:
for word in re.findall('[a-zA-Z_]+', string):
if word not in allowed_words:
raise ValueError(
'"{}" is forbidden to use in math expression'.format(word)
)
for old, new in replacements.items():
string = string.replace(old, new)
def func(x):
return eval(string)
return func
if __name__ == '__main__':
func = string2func(input('enter function: f(x) = '))
a = float(input('enter lower limit: '))
b = float(input('enter upper limit: '))
x = np.linspace(a, b, 250)
plt.plot(x, func(x))
plt.xlim(a, b)
plt.show()
Result: 结果:
$ python test.py
enter function: f(x) = x^2
enter lower limit: 0
enter upper limit: 2
And for a malicious user: 对于恶意用户:
enter function: f(x) = import subprocess; subprocess.check_call(['rm', '-rf', '*'], shell=True)
Traceback (most recent call last):
File "test.py", line 35, in <module>
func = string2func(input('enter function: f(x) = '))
File "test.py", line 22, in string2func
'"{}" is forbidden to use in math expression'.format(word)
ValueError: "import" is forbidden to use in math expression
import numpy as np
import matplotlib.pyplot as plt
# there should be a better way using regex
replacements = {
'sin' : 'np.sin',
'cos' : 'np.cos',
'exp': 'np.exp',
'^': '**',
}
# think of more security hazards here
forbidden_words = [
'import',
'shutil',
'sys',
'subprocess',
]
def string2func(string):
''' evaluates the string and returns a function of x '''
for word in forbidden_words:
if word in string:
raise ValueError(
'"{}" is forbidden to use in math expression'.format(word)
)
for old, new in replacements.items():
string = string.replace(old, new)
def func(x):
return eval(string)
return func
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.