Donnerstag, 27. Mai 2010

Python 049 Laplace-algorithm for calculating voltage between different potentials numerically



The white edges have a potential of 0 V. The two bodies inside have a potential of 30 V. The voltage in the space between has been calculated numerically with the laplace-algorithm.

from visual import *

ball = []
v = [] # v = voltage
vnew = [] # new calculated voltage
unchangeableflag = [] # if 1 --> value cannot be changed
size = 35 # size of the field
scene.center = (size/2, size/2, 0)
vmax = 100.0

# initalize
for n in range(size*size+size+1):
v.append(0)
vnew.append(0)
unchangeableflag.append(0)

# draw raster
for x in range(size):
for y in range(size):
ball.append([]) # x-pos, y-pos
ball[x*size+y] = sphere(pos=(x,y), radius = 0.4)

# set unchangeable potentials
for n in range(size):
v[n] = 0.0
unchangeableflag[n] = 1

for n in range(size):
v[n*size-1] = 0.0
unchangeableflag[n*size-1] = 1

for n in range(size):
v[n*size] = 0.0
unchangeableflag[n*size] = 1

for n in range(size):
v[size*size-size+n] = 0.0
unchangeableflag[size*size-size+n] = 1

v[250] = vmax
unchangeableflag[250] = 1
v[475] = vmax
unchangeableflag[475] = 1
print "set unchangeable potentials!"

# laplace-algorithm
for a in range(1000000):
for x in range(size):
for y in range(size):
if x % size != 1:
pass
if x % size != size - 1:
pass
if y % size != 1:
pass
if y % size != size - 1:
pass
if unchangeableflag[x*size+y] == 0:
vnew[x*size+y] = (v[(x+1)*size+y] + v[(x-1)*size+y] + v[x*size+y+1] + v[x*size+y-1]) / 4.0

# vnew --> v
colorfactor = 10.0
for x in range(size):
for y in range(size):
if unchangeableflag[x*size+y] == 0:
v[x*size+y] = vnew[x*size+y]
ball[x*size+y].color = (v[x*size+y]/10,0.2,0.2)
if v[x*size+y] >= 0.2 * vmax:
ball[x*size+y].color = ((abs(v[x*size+y]/colorfactor/5.0)),0,0)
else:
ball[x*size+y].color = (0,0,(abs(v[x*size+y]/colorfactor)))

Code with identation:

http://paste.pocoo.org/show/218999/

Keine Kommentare:

 
eXTReMe Tracker