I am trying to solve Newton 2nd law (F=ma) by numerical method using RK4 method. Below is the implementation of my code so far:
import numpy as np
import matplotlib.pyplot as plt
v0 = 1 # Initial velocity
theta = 45 # Launch angle
t0 = 0 # Start time
tf = 100 # End time
h = 1 # Steps
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
t = np.arange(t0,tf,h) # Time points
v = [Uy,Ux]
s = [Uy,Ux]
def velocity(v,t):
g = 9.81 # Acceleration of free fall
Vy = v[0] # Array for initial value
Vx = v[1] # Array for initial value
dVy_dt = -g
dVx_dt = 0
return [dVy_dt,dVx_dt]
def position(s,t):
g = 9.81 # Acceleration of free fall
Sy = s[0] # Array for initial value
Sx = s[1] # Array for initial value
dSy_dt = Sy - (g*t)
dSx_dt = Sx * t
return [dSy_dt,dSx_dt]
def RK4(func,t,h,y0):
nt = t.size
y = np.zeros(nt)
y[0] = y0
for n in range(0,nt - 1):
k1 = func(t[n],y[n])
k1 = func(t[n] + h/2,y[n] + h*k1/2)
k3 = func(t[n] + h/2,y[n] + h*k2/2)
k4 = func(t[n] + h,y[n] + h*k3)
y[n+1] = y[n] + (h*k1/6 + h*k2/3 + h*k3/3 + h*k4/6)
return y
Position_y = RK4(position(s,t)[0],t,h,s[0])
Position_x = RK4(position(s,t)[1],t,h,s[1])
I get the following error below:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-51-01727ad9bc4b> in <module>
50 return y
51
---> 52 Position_y = RK4(position(s,t)[0],t,h,s[0])
53 Position_x = RK4(position(s,t)[1],t,h,s[1])
<ipython-input-51-01727ad9bc4b> in RK4(func, t, h, y0)
42 y[0] = y0
43 for n in range(0,nt - 1):
---> 44 k1 = func(t[n],y[n])
45 k1 = func(t[n] + h/2,y[n] + h*k1/2)
46 k3 = func(t[n] + h/2,y[n] + h*k2/2)
TypeError: 'numpy.ndarray' object is not callable
I do not understand what the error means. Could the problem be my function call to RK4() is indexed wrongly? Could it be some other problem?
You are returning numpy array in function position(s,t)
and trying to call it as a function which is giving error
One of the solution is store the result of position(s,t)
in numpy array like [p1,p2]=position(s,t)
and then use Position_y = RK4(p1,t,h,s[0])
same for Position_x
Good Luck
Looks like you are assuming NP array as function, position(s,t)[0] returns np array, and you are using that as a callable func in RK4. change last 2 lines as,
Position_y = RK4(position,t,h,s[0])
Position_x = RK4(position,t,h,s[1])
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.