下面是對帶阻力的炮彈運動進行建模的代碼,其中 solve_euler 是一個預定義的函式,它生成一組陣列(如表格)的值。在這些值中,xs 和 ys 為這段代碼匯出,稱為 xs_euler 和 ys_euler。這些值是炮彈的 x 和 y 坐標,直到時間 t1(在 solve_euler 函式中使用的某個定義的數字,在本例中為 t1 = 300)。我現在想要做的是繪制新的 x 和 y 值的圖形(通過乘以速度和時間),顯示路徑如何根據發射角度而不同。以下是我目前所擁有的:
import math as m
import matplotlib.pylab as plot
import numpy
n_steps = 1000
theta = numpy.arange(m.pi/36, m.pi/2, m.pi/36)
v = 200
g = 9.81
initial_conditions = [0, 0, 88.38834764831843, 88.38834764831843]
values_euler = solve_euler(initial_conditions, 300, n_steps)
xs_euler, ys_euler = values_euler[:,0], values_euler[:,1]
plt.plot(xs_euler, ys_euler, color='blue', linestyle='--')
plt.xlim(0,1500)
plt.ylim(0,800);
t = numpy.linspace(0, 500, num=1000) # Set time as 'continous' parameter.
for i in theta: # Calculate trajectory for every angle
for k in t:
x = ((v*k)*xs_euler*numpy.cos(i)) # get positions at every point in time
y = ((v*k)*ys_euler*numpy.sin(i))-((0.5*g)*(k**2))
plot.plot(x1, y1) # Plot for every angle
plot.show() # And show on one graphic
很明顯,我不知道如何在回圈中使用 xs_euler 和 ys_euler,同時還能夠在時間和發射角度 (theta) 上進行回圈。有人可以告訴我我哪里出錯了以及如何解決嗎?
uj5u.com熱心網友回復:
我假設您希望所有時間點的圖形都是 y(t) vs x(t),在這種情況下,您需要在迭代每個 theta 時隨時間存盤 x 和 y 的所有值:
我的建議是為給定的 theta 創建一個 x 和 y 值串列,隨著時間的推移進行迭代。如果您不需要存盤它,則可以使用串列理解來覆寫 i 的每個值。如果你這樣做,我會把它寫到資料框的列中。
我有點困惑的另一件事是你的情節在某些情況下被稱為“plt”,而在其他情況下被稱為“情節”。我建議保持它與您匯入它的方式一致(在 中作為“情節” import matplotlib.pylab as plot)
for i in theta: # Calculate trajectory for every angle
x = [((v*k)*xs_euler*numpy.cos(i)) for k in t] # get positions at every point in time
y = [((v*k)*ys_euler*numpy.sin(i))-((0.5*g)*(k**2)) for k in t]
plot.plot(x, y) # Plot for every angle
plot.show()
uj5u.com熱心網友回復:
你的問題不在于編碼,而在于數學。
除非我不明白是什么solve_euler,否則你不需要修改xs_euleror ys_euler,那些已經是球在不同時間點的 x 和 y 坐標。但是該solve_euler函式只回傳一個初始條件的資料 - 這意味著如果你想要不同初始角度的資料,你需要再次呼叫它(你不能使用來自一個初始條件的資料來計算不同初始條件的軌跡。這個系統不能那樣作業 - 幾乎沒有系統可以)。
因此,您必須遍歷角度并每次呼叫 solve_euler ,并繪制它回傳的資料。
一些偽代碼:
create matplotlib figure, set all axes and whatnot
for angle-you-want-to-iterate-through:
vx0 = x-component of initial velocity (will have a cos(angle))
vy0 = y-component of initial velocity (will have a sin(angle))
initial conditions are [x0, y0, vx0, vy0]
data = result of solve_euler with the new initial conditions
plot data[:0] vs data[:1], label with angle
add a legend to plot
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/354234.html
標籤:Python 功能 循环 matplotlib 物理
