I wrote a function which returns me a certain array. Whenever I just print a certain value of this function, it works fine. However, if I try to remember certain values of the function as variables, it works for one variable, but afterwards it returns me an error, saying: “ValueError: setting an array element with a sequence.”
My code is as follows:
N=5
steps=10
delta_t=0.01 #these are just a bunch of constants
k_B=1
T=1
m=1
gamma=1
sigma=np.sqrt(2*k_B*T*m*gamma/delta_t)
a=16
q0=2*np.pi/a
def diff_array(V0, k_c, x0):
pos_array=np.empty([N+steps+1])
for i in range(N+steps+1):
pos_array[i]=0
def potential_force(x):
return (V0*np.pi)/a*np.sin(q0*x+np.pi)
for i in range(N):
x1=0
x2=0
v1=0
v2=0
x=0
G1_old=k_c*(-x0)+np.random.normal(0,sigma)+potential_force(0)
G2_old=-k_c*(-x0)+np.random.normal(0,sigma)+potential_force(0)
for j in range(steps):
F=k_c*(x2-x1-x0)
W1=np.random.normal(0,sigma)
W2=np.random.normal(0,sigma)
U1=potential_force(x1)
U2=potential_force(x2)
G1=F+W1+U1
G2=-F+W2+U2
x1=x1+delta_t*v1*(1-delta_t*gamma/2)+(delta_t)**2*G1/(2*m)
v1=(v1*(1-delta_t*gamma/2)+delta_t*(G1_old+G1)/(2*m))/(1+delta_t*gamma/2)
x2=x2+delta_t*v2*(1-delta_t*gamma/2)+(delta_t)**2*G2/(2*m)
v2=(v2*(1-delta_t*gamma/2)+delta_t*(G2_old+G2)/(2*m))/(1+delta_t*gamma/2)
G1_old=G1
G2_old=G2
x=(x1+x2)/2
pos_array[N+j+1]=pos_array[N+j+1]+(x**2-pos_array[N+j+1])/(i+1)
pos_array[i]=x1**2
return pos_array
Apparently, calling this function in a second variable causes the variable x to be seen as a sequence. But if I just call this function, i.e. in a print, it works just fine. What is going on?
Michael Henchard is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.