我的代码存在问题。该代码假设在框中找到线性电位(V)。它给出了一个我以前没见过的错误。 虽然错误似乎符合逻辑的代码。任何人都可以解释为什么会发生在哪里"如果delta0>增量"
提前谢谢你,
这是我的代码
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 11:32:00 2015
@author: 50073507
"""
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import axes3d
np.set_printoptions(formatter={'float': '{: 0.2f}' . format})
def relax(v):
return (v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1])
tolerance = 1.e-6
delta = 1.0
nx =7
ny = 7
v = np.zeros([nx,ny])
v[:,0] = -1
v[:,-1] = 1
v[0,:] = np.linspace(-1,1,nx)
v[ny-1,:] = np.linspace(-1,1,nx)
print("starting values")
print(v)
iteration = 0
while delta > tolerance:
delta = 0
for i in range(1,nx-1):
for j in range(1,ny-1):
newVij = relax(v)
delta0 = np.abs(newVij - v[i,j])
if delta0 > delta:
delta = delta0
v[i,j] = newVij
iteration += 1
print ("Iteration", iteration)
print(v)
x = np.linspace(-1,1,nx)
y= np.linspace(-1,1,ny)
x, y = np.meshgrid(x,y)
fig = plt.figure()
ax = fig.add_subplot(111, projection = '3d')
surf = ax.plot_surface(x, y, v , alpha = 0.7, cmap = cm.coolwarm)
cset = ax.contourf(x,y,v,zdir='v',offset=-1,cmap=cm.coolwarm)
plt.show()
Ey, Ex = np.gradient(-v)
fig , ax = plt.subplots()
ax.quiver(x,y, Ex, Ey, y)
ax.set(aspects = 1, title = 'Eletric Field')
plt.axis([-1.05, 1.05,-1.05,1.05])
plt.show()
答案 0 :(得分:0)
您正在尝试将元组与浮点数进行比较。检查你的功能:
def relax(v):
return (v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1])
这将返回元组(v[i-1,j] + v[i+1, j], + v[i,j-1] + v[i,j+1])
。
在while
你得到了这个:
newVij = relax(v)
delta0 = np.abs(newVij - v[i,j])
if delta0 > delta:
好吧,delta0是一个元组,delta是一个浮点数,这就是问题所在。