有没有办法在 python 中绘制“函数字符串”?

芝士蛋糕电视

示例:用户在终端中键入“(x^2 + 5)^3”,脚本会像 WolframAlpha 那样绘制函数。

在python中有没有简单的方法来做到这一点?

该函数可能包括 abs()、sqrt() 等。

提前感谢您的回复

简洁详细21

您可以尝试将 eval 与输入的 X 或默认 x 一起使用:

import matplotlib.pyplot as plt
import numpy as np
import re


def get_variables(input_string):
    count = 0
    matches = re.findall(r'(?i)[a-z]', input_string)
    return set(matches) #returns unique variables

function = input('Input Function: ')
variables = get_variables(function)
print(variables, type(variables), function)
varDict = {v: np.arange(100) for v in variables} #maps the variable names to some default range
for v in variables: #changes the function string to work with the newly defined variables
    pattern = r'\b%s\b' %v
    function = re.sub(pattern,r'varDict["%s"]' %v,function)
answer = eval(function) #evaluates the function


if len(variables) == 1:
    plt.plot(*varDict.values(),answer) #plot the results, in this case two dimensional
else:
    ax = plt.axes(projection="3d")
    ax.plot3D(*varDict.values(),answer) # line
    #ax.scatter3D(*varDict.values(),answer); #scatter
    
plt.show()

如果您想要散点图或添加逻辑来制作形状(即使用网格网格),您可以更改 3d 设置

只需确保 eval 语句已完全清理。这也要求函数以python语法输入(**不是^),除非你想添加函数来编辑字符串中的常见语法差异。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

有没有办法镜像python函数?

有没有办法反转这个python函数?

有没有办法在python的lambda中执行“ if”

有没有办法在python中禁止舍入?

有没有办法在python中重载+ =?

有没有办法在Python中包含±(正负)?

有没有办法在python中清除屏幕?

有没有办法在python中输入小写?

有没有办法摆脱python列表中的“'”?

有没有办法在python中打印not bool?

有没有办法使用 Python 从 JSON 文件中删除某些字符串?

有没有办法在Python中解码字符串对象内的字节?

有没有办法只从 python 列表中输出字符串格式的数字?

有没有办法知道Python中没有索引的列表的哪个数字?

有没有办法在字符串列表python中查找特定字符?

有没有办法关闭python中没有文件对象的文件?

有没有办法在python中绘制z值

有没有办法在 Python 中触发不正确的字符串输入的异常?

有没有办法使此Python kNN函数更有效?

有没有办法显示HTML中python数组中的所有元素?

有没有办法在Python中更改有效的进程名称?

有没有办法在Python中覆盖现有(系统)类上的方法?

有没有办法在 Python 中执行固定持续时间的函数?

有没有办法在python中添加.replace函数?

有没有办法从python中的调用函数访问变量?

有没有办法循环遍历python中的函数?

有没有办法为python中的内置函数添加额外的属性?

有没有办法在 Python 中获取 ASCII 字符?

有没有办法为Python对象的所有成员打印文档字符串的简短版本?