如何用Sympy绘制点?

2024-10-03 04:24:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算一个函数,它的前两个导数。然后,我需要在图上画出原始函数的最小点和最大点。我已经计算过这些,但不知道如何绘制数据。 最小/最大点的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();

当我运行程序时,我得到这个错误。 `在

^{pr2}$

我试着把点标在p上,得到了一个不同的错误

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

有没有办法在这张图上画点?(p)


Tags: theto函数inforplot错误diff
3条回答

{{55y>在这种情况下,{55y}可以用来定义cd1}中的临界点。在

数组是构造的,但是如果在numpy.transpose步骤中绘制的常量值有问题,则可能不具有相同的长度。因此,在第一个matplotlib.pyplot之前传递一个条件。在

from sympy import *
import numpy as np
import matplotlib.pyplot as plt

x = symbols('x')
equation = x**2 + 2 #OK = x*exp(-x**2/10) OR x**2 + 2
firstDeriv = equation.diff(x)
secondDeriv = firstDeriv.diff(x)
criticalPoints = list(solveset(firstDeriv, x))
criticalPointsY = [equation.subs(x, a) for a in criticalPoints]
xx = np.linspace(-10, 10, 100)
lam_f= lambdify(x, [equation, firstDeriv, secondDeriv])
yy=[elem if  type(elem) == np.ndarray else np.full(len(xx), elem) for elem in lam_f(xx)]
plt.plot(xx, np.transpose(yy))
plt.plot(criticalPoints, criticalPointsY, 'k*')
plt.show()

enter image description here

我已经解决了这个问题。这种困境的出现是因为方程组的导数要么不存在,要么是一条水平线。在

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

我在这段代码中所做的是通过将方程转换为字符串来测试,看看是否存在x值。如果有一个,我将把这个方程附加到一个数组中,我们稍后将访问这个数组,否则,我将绘制水平线。我还翻转一个bool,告诉我们,如果我们有一个带有变量的方程。在

^{pr2}$

如果我们有方程,我们把所有的非水平方程都加到数组中,然后把它们画出来。在

^{3}$

SymPy图可以与^{}组合。但是,SymPy打印类型不包括点打印,这正是您想要的临界点。在这种情况下,应该直接使用matplotlib,SymPy无论如何都会暗地里这么做。在

下面是一个基于您的代码的示例,但是没有分号,具有列表理解功能,并且matplotlib用于所有绘图。注意,lambdify提供了一种在一组点上高效地计算一组SymPy表达式的方法。在

from sympy import *
import numpy as np
import matplotlib.pyplot as plt

x = symbols('x')
equation = x*exp(-x**2/10)
firstDeriv = equation.diff(x)
secondDeriv = firstDeriv.diff(x)
criticalPoints = list(solveset(firstDeriv, x))
criticalPointsY = [equation.subs(x, a) for a in criticalPoints]
xx = np.linspace(-10, 10, 1000)
yy = lambdify(x, [equation, firstDeriv, secondDeriv])(xx)
plt.plot(xx, np.transpose(yy))
plt.plot(criticalPoints, criticalPointsY, 'k*')
plt.show()

plot

相关问题 更多 >