Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
360 views
in Technique[技术] by (71.8m points)

python - Using Sympy Equations for Plotting

What is the best way to create a Sympy equation, do something like take the derivative, and then plot the results of that equation?

I have my symbolic equation, but can't figure out how to make an array of values for plotting. Here's my code:

from sympy import symbols
import matplotlib.pyplot as mpl

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)

nums = []
for i in range(1000):
    nums.append(t)
    t += 0.02

plotted = [x for t in nums]

mpl.plot(plotted)
mpl.ylabel("Speed")
mpl.show()

In my case I just calculated the derivative of that equation, and now I want to plot the speed x, so this is fairly simplified.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use numpy.linspace() to create the values of the x axis (x_vals in the code below) and lambdify().

from sympy import symbols
from numpy import linspace
from sympy import lambdify
import matplotlib.pyplot as mpl

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)
lam_x = lambdify(t, x, modules=['numpy'])

x_vals = linspace(0, 10, 100)
y_vals = lam_x(x_vals)

mpl.plot(x_vals, y_vals)
mpl.ylabel("Speed")
mpl.show()

(improvements suggested by asmeurer and MaxNoe)

enter image description here

Alternatively, you can use sympy's plot():

from sympy import symbols
from sympy import plot

t = symbols('t')
x = 0.05*t + 0.2/((t - 5)**2 + 2)

plot(x, (t, 0, 10), ylabel='Speed')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...