如何用Sympy绘制点?

扎克

我需要计算和绘制一个函数,它是前两个导数。然后,我需要在图表上绘制原始函数的最小和最大点。我已经计算了这些,但是对于如何绘制数据图形却迷失了。最小/最大点的x值为criticalPoints[]

y值为

criticalPointsY[]

这是出现错误的代码段。

equation=CreateFunction();
    firstDeriv=equation.diff(x);
    secondDeriv=firstDeriv.diff(x);
    print(equation);
criticalPoints=solveset(firstDeriv,x);
criticalPointsY=[];
for a in criticalPoints:
    criticalPointsY.append(equation.subs(x,a));

p=plot(equation,firstDeriv,secondDeriv,(x,-10,10));
# Need to add the critical points to the graph. We have them, and the
# y values, but need to put them on the graphs.
print(criticalPoints)
print(criticalPointsY);
for a in range(0, len(criticalPoints)):
    xval=criticalPoints[a];
    yval=criticalPointsY[a];
    plt.plot(xval, yval, 'ro')
p.show();
plt.show();

运行程序时,出现此错误。`

Traceback (most recent call last):
  File "--------", line 58, in <module>
    xval=criticalPoints[a];
TypeError: 'FiniteSet' object does not support indexing

我尝试在p上绘制点并得到不同的错误

    p.plot(criticalPoints,criticalPointsY);
AttributeError: 'Plot' object has no attribute 'plot'

有没有办法在此图上绘制点?(p)

扎克

我已经解决了这个问题。由于方程的导数可能不存在,或者水平线,因此出现了难题。

x = symbols('x')
UserInput()
equation = CreateFunction()
firstDeriv = equation.diff(x)
secondDeriv = firstDeriv.diff(x)
workingEquations=[]
hasEquations=False

我在此部分所做的是通过将方程式转换为字符串并查看是否存在x值来进行测试。如果存在,则将方程式附加到稍后将访问的数组中,否则,将绘制水平线。我还翻了个布尔,稍后再告诉我们是否有一个带变量的方程。

if(not str(equation).find("x")==-1):
    workingEquations.append(equation)
    hasEquations=True
    print("True")
else:
    plt.axhline(y=equation)
if(not str(firstDeriv).find("x")==-1):
    workingEquations.append(firstDeriv)
else:
    plt.axhline(y=firstDeriv)
if(not str(secondDeriv).find("x")==-1):
    workingEquations.append(secondDeriv)
else:
    plt.axhline(y=secondDeriv)
try:
    criticalPoints = list(solveset(firstDeriv, x))
    criticalPointsY = [equation.subs(x, a) for a in criticalPoints]
    plt.plot(criticalPoints, criticalPointsY, 'k*')
except:
    print("No critical points")

如果我们有方程式,则可以从该数组中绘制出它们的图形,并在其中附加所有非水平方程式。

if(hasEquations):
    xx = np.linspace(-10, 10, 1000)
    yy = lambdify(x, workingEquations)(xx)
    plt.plot(xx, np.transpose(yy))
plt.show()

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章