Python:尝试多次运行函数并为每次运行保存值

时间:2018-05-17 08:55:01

标签: python

我正在尝试从我正在运行的数值模拟中获取一些数据。 我有一个函数可以解决我的ODE并将我需要的值保存在向量rv中。我想运行我的函数1000次并获得每个时间步的rv的平均值,但我无法弄清楚如何去做。

我的第一个想法是调用函数1000次并将数据保存在数组中。

for i in range(1000):
    datavector = np.array(0)
    circle(N,dt,x0,y0,phi0,r,T,nu,v,Omega,R)
    datavector = np.append(datavector, rv)

但是当我这样做时,我收到以下错误消息: NameError: name 'rv' is not defined

我附上我的代码,因为我不太擅长解释。对不起它太乱了

import math
import numpy as np
import matplotlib.pyplot as plt

def circle(N,dt,x0,y0,phi0,r,T,nu,v,Omega,R):


kB = 1.38*10**-23 # Boltzmann constant [J/K]plt #math constants
DT = kB*T/(6*math.pi*nu*r)  # Translational diffusion coefficent [m^2/s]
DR = kB*T/(8*math.pi*nu*r**3) # Rotational diffusion coefficent [rad^2/s]
n = 0 #iteration constant


x=x0 #vectors and initial values
y=y0
phi=phi0
phiv= np.array(phi) #vector containing phi-values
xv= np.array(x) #vector containing x-values
yv= np.array(y) #vector containing y-values
rv=np.array(np.sqrt(x**2+y**2))
xss=np.array(x) #vector containing start and (soon) end value
yss=np.array(y) # same as above

phiK=math.sqrt(2*DR*dt) #constants used in the iteration
xyK=math.sqrt(2*DT*dt)
Odt=Omega*dt

while n < N: #from 0 -> N-1
    phi = phi + Odt + phiK*np.random.normal(0,1) #eq (9)
    x = x + v*math.cos(phi)*dt + xyK*np.random.normal(0,1) #eq (10)
    y = y + v*math.sin(phi)*dt + xyK*np.random.normal(0,1) #eq (11)
    if (x**2+y**2) > R**2: #if the particle is outside the boundary
        if abs(x) > R: #need to make sure arccos(x/R) is meaningful
            xn = np.sign(x)*R
            theta = np.sign(y)*np.arccos((xn/R))#angle to particle
        else:
            theta = np.sign(y)*np.arccos((x/R))#angle to particle  
        rp = np.array([x,y]) #r for the particle
        rr = np.array([np.cos(theta)*R,np.sin(theta)*R]) #r for the boundary closest to the particle
        #d = rp - rr #smallest distance from particle to boundary
        q = (2*np.linalg.norm(rr)/np.linalg.norm(rp)) - 1
        x = q*np.array(rp[0]) #x- and y-value forced inside the boundary
        y = q*np.array(rp[1])

    phiv = np.append(phiv, phi) #adding all phi-values to a vector
    xv = np.append(xv, x) # adding all x-values to a vector
    yv = np.append(yv, y) # adding all y-values to a vector'
    rv = np.append(rv,(np.sqrt(x**2+y**2)))
    n=n+1 #iteration 


return(rv)
#print(rv)

for i in range(2): #run the program a number of times
    datavector = np.array(0)
    circle(1E5,1E-3,0*np.random.uniform(-1E-5,1E-5),0*np.random.uniform(-1E-5,1E-5),np.random.uniform(-2*np.pi,2*np.pi),1E-6,300,1E-3,5*1E-6,0,2E-5)
    datavector = np.append(datavector, rv)
np.savetxt('testet.txt', datavector)

1 个答案:

答案 0 :(得分:0)

name 'rv' is not defined表示在对其进行操作之前尚未定义您的变量。

根据您提供的信息,rv永远不会定义。最重要的是,您在每次迭代时重新初始化结果向量datavector,而它应该只在主循环之前初始化。

我认为rvcircle的返回值。

因此,对代码的更正应如下所示:

datavector = []
for i in range(1000):
    rv = circle(N,dt,x0,y0,phi0,r,T,nu,v,Omega,R)
    datavector.append(rv)