I am trying to solve a set of differential equations in x,y,z, I have made simple kutta 2 code in python before but not with 3 variables. I am not sure if what i have done is an acceptable way to adjust for 3. Here is what i have so far: (i have not entered the exact solution as i do not know it)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define function to compute velocity field
A = 0.2
B = 1.0
C = 0.20
def velfun(x,y,z,t):
xvelocity = (A*np.sin(z) + C*np.cos(x))
yvelocity = (B*np.sin(x) + A*np.cos(z))
zvelocity = (C*np.sin(y) + B*np.cos(x))
return xvelocity, yvelocity, zvelocity
# Set stopping time
# and the step length
Nstep = 10000
h = 0.01
# Create arrays to store x and t values
x = np.zeros(Nstep);
y = np.zeros(Nstep);
z = np.zeros(Nstep);
# Set the initial condition
x[0] = 1
y[0] = 0
z[0] = 0
# Carry out steps in a loop
for k in range(1,Nstep):
# Provisional Euler step
xx = x[k-1]
yy = y[k-1]
zz = z[k-1]
ux,uy,uz = velfun(xx,yy,zz)
xp = x[k-1] + h*ux
yp = y[k-1] + h*uy
zp = z[k-1] + h*uz
# Compute velocity at provisional point
uxp,uyp,uzp = velfun(xp,yp,zp)
# Compute average velocity
uxa = 0.5*(ux + uxp)
uya = 0.5*(uy + uyp)
uza = 0.5*(uz + uzp)
# Make final Euler step
# using average velocity
x[k] = x[k-1] + h*uxa
y[k] = y[k-1] + h*uya
z[k] = z[k-1] + h*uza
# Exact solution
# Plot results
fig = plt.figure()
ax = plt.axes(projection='3d')
ax = plt.axes(projection='3d')
ax.scatter3D(x,y,z,'b',label='x (with RK2)')
plt.show()
velfun
expects four parameters but you only ever pass three. \$\endgroup\$