我创建了一些代码:
import numpy as np
Length=(2.7)*10**-3
Nx=4
x = np.linspace(0, Length, Nx+1) # mesh points in space
t1=110
t2=100
m=((t2-t1)/Length)
T=5
N=5
t = np.linspace(0, T, N+1)
Coeff=0.5
b=0.2
tamb = 20
u = np.zeros(Nx+1)
u_1 = np.zeros(Nx+1)
for i in range(0, Nx+1):
u_1[i] = m*(x[i])+t1
#print u_1
r=[]
for n in range(0, N+1):
# Compute u at inner mesh points
for i in range(0,1):
u[i] = 2*Coeff*(u_1[i+1]+b*tamb)+(1-2*Coeff-2*b*Coeff)*u_1[i]
for i in range(1,Nx):
u[i] = Coeff*(u_1[i+1]+u_1[i-1])+(1-2*Coeff)*u_1[i]
for i in range(Nx,Nx+1):
u[i] = 2*Coeff*(u_1[i-1])+(1-2*Coeff)*u_1[i]
# Switch variables before next step
u_1, u = u, u_1
r.append(u.copy())
print r[5]
代码输出:
[ 78.1562 94.1595 96.82 102.6375 102.125 ]
使用我创建了一个应用于数组的函数的代码:
def function(data,time):
import numpy as np
Values=data[n]
Length=(Values[2])*10**-3
Nx=4
x = np.linspace(0, Length, Nx+1) # mesh points in space
t1=Values[0]
t2=Values[1]
m=((t2-t1)/Length)
T=time[5]
N=5
t = np.linspace(0, T, N+1)
Coeff=0.5
b=0.2
tamb = 20
u = np.zeros(Nx+1)
u_1 = np.zeros(Nx+1)
for i in range(0, Nx+1):
u_1[i] = m*(x[i])+t1
#print u_1
r=[]
for n in range(0, N+1):
# Compute u at inner mesh points
for i in range(0,1):
u[i] = 2*Coeff*(u_1[i+1]+b*tamb)+(1-2*Coeff-2*b*Coeff)*u_1[i]
for i in range(1,Nx):
u[i] = Coeff*(u_1[i+1]+u_1[i-1])+(1-2*Coeff)*u_1[i]
for i in range(Nx,Nx+1):
u[i] = 2*Coeff*(u_1[i-1])+(1-2*Coeff)*u_1[i]
# Switch variables before next step
u_1, u = u, u_1
r.append(u.copy())
return r
import numpy as np
#arrays
data=np.array(((110,100,2.5),(112,105,2.6),(115,109,2.7)))
time=np.array((0,1,2,3,4,5))
#apply function to array
for n in range(len(data)):
r = function(data,time)
print r[5]
第一个代码工作正常,但是当我使用函数(第二个代码)应用代码时,如果我告诉我得到以下错误:
Traceback (most recent call last):
File "C:/Users/a/Desktop/functiontrial3.py", line 39, in <module>
r = function(data,time)
File "C:/Users/a/Desktop/functiontrial3.py", line 3, in function
Values=data[n]
UnboundLocalError: local variable 'n' referenced before assignment
我必须做什么才能使以下代码正常工作?