matplotlib 如何从字符串绘制数学函数

elcex8rz  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(135)

我有一个字符串"x * (x - 32 ( 2 /x) )",它表示一个数学函数。我如何使用pythonmatplotlib将这个字符串转换为一个要绘制的点数组?

mfpqipee

mfpqipee1#

你可以使用Python的eval函数将字符串转换成代码,但这是危险的,通常被认为是不好的风格

如果用户可以输入字符串,他们可以输入像import subprocess; subprocess.check_call(['rm', '-rf', '*'], shell=True)这样的东西。
因此,请确保您在其中构建了合理的安全性。
你可以定义一个函数,它接受一个字符串并返回一个函数。我们需要做一点预处理,让用户更像他习惯的那样输入公式(^等):

白名单代替黑名单

定义允许和支持的单词似乎比将一些单词列入黑名单更好:

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()

测试结果:

$ python test.py
enter function: f(x) = x^2
enter lower limit: 0
enter upper limit: 2

对于恶意用户:

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

相关问题