Using result of array (potential) to find electric field in Python

  arrays, numerical-methods, numpy, physics, python

I am new to python and stack overflow. I am trying to find both the electric Potential and E field of a box with 0 potential in all sides except top V = 10. I have the potential part now, but not sure how to use the array (result) of found potential V in the code to calculate E. I have to take the derivative of all components in array above so E = Del(V) = d/dx(Vx) + d/dy(Vy). I am getting many type errors using the array V. How would I correctly use the values in the array above or result of V[i, j] in code to calculate E and obtain a contour or figure of E? Any help/advice is appreciated.


    
import numpy as np
import matplotlib.pyplot as plt
from numpy import diff


#Max iteration
maxIter = 500

#Dimension and delta
lenX = lenY = 8 
delta = 1

# Boundary condition
Vtop = 10
Vbottom = 0
Vleft = 0
Vright = 0

# Initial guess of interior grid
Vguess = 5

# colour interpolation and colour map
colorinterpolation = 50
colourMap = plt.cm.jet

# meshgrid
X, Y = np.meshgrid(np.arange(1, lenX+1), np.arange(1, lenY+1))

#  Array size and value Vguess
V = np.empty((lenX, lenY))
V.fill(Vguess)

E = np.empty((lenX, lenY))



# Boundary conditions
V[(lenY-1):, :] = Vtop
V[:1, :] = Vbottom
V[:, (lenX-1):] = Vright
V[:, :1] = Vleft

#  Assume iteration convergences w/in maxIter = 500)
for iteration in range(0, maxIter):
    for i in range(1, lenX-1, delta):
        for j in range(1, lenY-1, delta):
            V[i, j] = 0.25 * (V[i+1][j] + V[i-1][j] + V[i][j+1] + V[i][j-1])
           



# does not work to find E countour z not same as x y    
        # dVdx = np.gradient(-V, i)
        # dVdy = np.gradient(-V, j)
        #E  = dVdx + dVdy #?
        #Ex = np.gradient(-V, i)
        #new loop here will not work? same type error V or contour error 
        #E[i, j] = np.gradient(-V, i) + np.gradient(-V, j) 
        #E[i, j] = np.gradient(-V[i]) + np.gradient(-V[j])


#does not work wrong answer
# E = np.diff(V)
#print(type(V));
#print(E);
                    



# Configure the contour
plt.title("Contour of Potential")
plt.contourf(X, Y, V, colorinterpolation, cmap=colourMap)
# Set Colorbar
plt.colorbar()
#Show Result
plt.show()
print("")


 # E = np.diff(V) #does not work
# print(E);
 # plt.plot(E)



# Configure the contour
# plt.title("Contour of Electric Field")
#plt.contourf(X, Y, E, colorinterpolation, cmap=colourMap)
# Set Colorbar
#plt.colorbar()
#Show Result
#plt.show()
#print("")



# # plt.figure(2)
# plt.figure(figsize=(6.0, 4.0))
# plt.xlim(0.0, lenX )
# plt.ylim(0.0, lenY);
# plt.plot(E) 
# # plt.xlabel('Distance ')
# # plt.ylabel('Temp. ')
# plt.show()
    




Source: Python Questions

LEAVE A COMMENT