I am writing a python code for my Ordinary differential Equations class which I have to model Newton's 2nd Law of motion using a numerical method (RK4). I believe my code is correct as i have worked out the differential equations by hand myself and verified the results.
I would Like to cut down the length of my code my grouping the similar ODE functions together but I have come across an error regarding the return type. Below is my work so far:
import numpy as np
import matplotlib.pyplot as plt
t0 = 0.0 # Start time
tf = 10.0 # End time
h = 0.001 # step size
t = np.arange(t0,tf,h) # Time Points
v0 = 20 # Initial velocity in m/s
theta = 45 # Launch angle
Uy = v0 * np.sin(theta*np.pi/180) # Initial velocity in y component
Ux = v0 * np.cos(theta*np.pi/180) # Initial velocity in x component
def velocity_y(t,v):
g = 9.81 # Acceleration of free fall
dVy_dt = -g
return dVy_dt
def velocity_x(t,v):
dVx_dt = 0
return dVx_dt
def velocity_xy(t,v):
g = 9.81 # Acceleration of free fall
dVy_dt = -g
dVx_dt = 0
return np.array([dVy_dt,dVx_dt])
p1,p2 = velocity_xy(t,v)
def rk4( f, x0, t):
n = len( t )
x = np.zeros(n)
x[0] = x0
for i in range( n - 1 ):
h = t[i+1] - t[i]
k1 = h * f( x[i], t[i] )
k2 = h * f( x[i] + 0.5 * k1, t[i] + 0.5 * h )
k3 = h * f( x[i] + 0.5 * k2, t[i] + 0.5 * h )
k4 = h * f( x[i] + k3, t[i+1] )
x[i+1] = x[i] + ( k1 + 2.0 * ( k2 + k3 ) + k4 ) / 6.0
return x
r = rk4(velocity_y,Uy,t)
r1 = rk4(velocity_x,Ux,t)
plt.plot(t,r1,'gx',linestyle='-',label='Velocity in y direction')
plt.xlabel('t or x')
plt.ylabel('v(t) or y(x)')
plt.legend()
plt.grid()
plt.show()
I implemented my ODE functions as below:
def velocity_y(t,v):
g = 9.81 # Acceleration of free fall
dVy_dt = -g
return dVy_dt
def velocity_x(t,v):
dVx_dt = 0
return dVx_dt
def velocity_xy(t,v):
g = 9.81 # Acceleration of free fall
dVy_dt = -g
dVx_dt = 0
return np.array([dVy_dt,dVx_dt])
p1,p2 = velocity_xy(t,v)
I am trying to group similar ODEs into the same function kinds so as to avoid over creating new functions just to define new ODEs.
def velocity_xy(t,v):
g = 9.81 # Acceleration of free fall
dVy_dt = -g
dVx_dt = 0
return np.array([dVy_dt,dVx_dt])
I believe the error is:
p1,p2 = velocity_xy(t,v)
but I do not know the proper syntax. The error from the program:
NameError Traceback (most recent call last)
<ipython-input-37-4ce3cb1658cb> in <module>
30 return np.array([dVy_dt,dVx_dt])
31
---> 32 p1,p2 = velocity_xy(t,v)
33 #-----------------------------------------------------------------------------
34
NameError: name 'v' is not defined
I would appreciate any helpful answers and comments.
I belive the main problem is that you are passing v as parameters for your def velocity_xy(t,v)
function but not declaring it's value anywhere in your code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.