Search code examples
pythonnumpygradientphysics

Calculating gradient using numpy


I'm trying to calculate and plot the electric field from a point charge, which is given by negative gradient of potential of a point charge. I wanted to use np.gradient for this.

Here's my code:

import numpy as np
import matplotlib.pyplot as plt

q = [10, 10, 1]  # cooridnates (x,y) and value of charge of point charge
vmin, vmax = 0, 32
x = y = np.linspace(vmin, vmax, 100)

X, Y = np.meshgrid(x, y)
potential = q[2] / np.sqrt((X - q[0]) ** 2 + (Y - q[1]) ** 2)
e_field = np.gradient(potential)

s = max(np.max(e_field[0]), np.max(e_field[1])) * 0.1
plt.quiver(x, y, -e_field[0], -e_field[1], units='xy', pivot='tail', width=0.03, scale=s)
plt.xlabel('x')
plt.ylabel('y')
plt.show()

I tried to calculate it like this using np.meshgrid and np.gradient but for some reason when you look at the plot it seems that the point charge attracts other positive charges diagonally and repels anti-diagonally. It obviously can't be the case, a positive point charge should repel in every direction and arrows should point outwards in all directions. What is wrong with my code?


Solution

  • Nevermind, I solved the problem just by switching the order of e_field[0] and e_field[1] in plt.quiver. Apparently that's all it was.