示例:用户在终端中键入“(x^2 + 5)^3”,脚本会像 WolframAlpha 那样绘制函数。
在python中有没有简单的方法来做到这一点?
该函数可能包括 abs()、sqrt() 等。
提前感谢您的回复
您可以尝试将 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] 删除。
我来说两句